This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.py
968 lines (844 loc) · 36.7 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
###
# Copyright (c) 2011, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
from __future__ import division
import re
import sys
import time
import json
import operator
import functools
import threading
import supybot.log as log
import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.ircmsgs as ircmsgs
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.registry as registry
import supybot.callbacks as callbacks
if sys.version_info[0] < 3:
import htmlentitydefs
else:
import html.entities as htmlentitydefs
from imp import reload
try:
from supybot.i18n import PluginInternationalization
from supybot.i18n import internationalizeDocstring
_ = PluginInternationalization('Twitter')
except:
# This are useless functions that's allow to run the plugin on a bot
# without the i18n plugin
_ = lambda x:x
internationalizeDocstring = lambda x:x
# We don't use oauth2 directly, but we try to import it here
# so we can tell the user it is missing.
try:
import oauth2
except ImportError:
raise callbacks.Error('You need the python-oauth2 library.')
try:
import twitter
except ImportError:
raise callbacks.Error('You need the python-twitter library.')
except Exception as e:
raise callbacks.Error('Unknown exception importing twitter: %r' % e)
reload(twitter)
if not hasattr(twitter, '__version__') or \
twitter.__version__.split('.') < ['0', '8', '0']:
raise ImportError('You current version of python-twitter is to old, '
'you need at least version 0.8.0, because older '
'versions do not support OAuth authentication.')
class ExtendedApi(twitter.Api):
"""Api with retweet support."""
def PostRetweet(self, id):
'''Retweet a tweet with the Retweet API
The twitter.Api instance must be authenticated.
Args:
id: The numerical ID of the tweet you are retweeting
Returns:
A twitter.Status instance representing the retweet posted
'''
if hasattr(self, '_oauth_consumer') and not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
try:
if int(id) <= 0:
raise TwitterError("'id' must be a positive number")
except ValueError:
raise TwitterError("'id' must be an integer")
url = 'https://api.twitter.com/1.1/statuses/retweet/%s.json' % id
data = self._FetchUrl(url, post_data={'dummy': None})
data = json.loads(data)
self._CheckForTwitterError(data)
return twitter.Status.NewFromJsonDict(data)
_tco_link_re = re.compile('http://t.co/[a-zA-Z0-9]+')
def expandLinks(tweet):
if 'Untiny.plugin' in sys.modules:
def repl(link):
return sys.modules['Untiny.plugin'].Untiny(None) \
._untiny(None, link.group(0))
return _tco_link_re.sub(repl, tweet)
else:
return tweet
def fetch(method, maxIds, name):
if name not in maxIds:
maxIds[name] = None
if maxIds[name] is None:
tweets = method()
else:
tweets = method(since_id=maxIds[name])
if not tweets:
return []
if maxIds[name] is None:
maxIds[name] = tweets[0].id
return []
else:
maxIds[name] = tweets[0].id
return tweets
@internationalizeDocstring
class Twitter(callbacks.Plugin):
"""Add the help for "@plugin help Twitter" here
This should describe *how* to use this plugin."""
threaded = True
def __init__(self, irc):
self.__parent = super(Twitter, self)
callbacks.Plugin.__init__(self, irc)
self._apis = {}
self._died = False
if world.starting:
try:
self._getApi().PostUpdate(_('I just woke up. :)'))
except:
pass
self._runningAnnounces = []
try:
conf.supybot.plugins.Twitter.consumer.key.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.consumer.secret.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.key.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.secret.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.durl.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.duser.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.dkey.addCallback(
self._dropApiObjects)
conf.supybot.plugins.Twitter.accounts.channel.api.addCallback(
self._dropApiObjects)
except registry.NonExistentRegistryEntry:
log.error('Your version of Supybot is not compatible with '
'configuration hooks. So, Twitter won\'t be able '
'to apply changes to the consumer key/secret '
'and token key/secret unless you reload it.')
self._shortids = {}
self._current_shortid = 0
def _dropApiObjects(self, name=None):
self._apis = {}
def _getApi(self, channel):
if channel in self._apis:
# TODO: handle configuration changes (using Limnoria's config hooks)
return self._apis[channel]
if channel is None:
key = self.registryValue('accounts.bot.key')
secret = self.registryValue('accounts.bot.secret')
url = self.registryValue('accounts.bot.api')
else:
key = self.registryValue('accounts.channel.key', channel)
secret = self.registryValue('accounts.channel.secret', channel)
url = self.registryValue('accounts.channel.api')
if key == '' or secret == '':
return ExtendedApi(base_url=url)
api = ExtendedApi(consumer_key=self.registryValue('consumer.key'),
consumer_secret=self.registryValue('consumer.secret'),
access_token_key=key,
access_token_secret=secret,
base_url=url)
self._apis[channel] = api
return api
def _get_shortid(self, longid):
characters = '0123456789abcdefghijklmnopwrstuvwyz'
id_ = self._current_shortid + 1
id_ %= (36**4)
self._current_shortid = id_
shortid = ''
while len(shortid) < 3:
quotient, remainder = divmod(id_, 36)
shortid = characters[remainder] + shortid
id_ = quotient
self._shortids[shortid] = longid
return shortid
def _unescape(self, text):
"""Created by Fredrik Lundh (http://effbot.org/zone/re-sub.htm#unescape-html)"""
text = text.replace("\n", " ")
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except (ValueError, OverflowError):
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
def __call__(self, irc, msg):
super(Twitter, self).__call__(irc, msg)
irc = callbacks.SimpleProxy(irc, msg)
for channel in irc.state.channels:
if self.registryValue('announce.interval', channel) != 0 and \
channel not in self._runningAnnounces:
threading.Thread(target=self._fetchTimeline,
args=(irc, channel),
name='Twitter timeline for %s' % channel).start()
def _fetchTimeline(self, irc, channel):
if channel in self._runningAnnounces:
# Prevent race conditions
return
lastRun = time.time()
maxIds = {}
self._runningAnnounces.append(channel)
try:
while not irc.zombie and not self._died and \
self.registryValue('announce.interval', channel) != 0:
while lastRun is not None and \
lastRun+self.registryValue('announce.interval', channel)>time.time():
time.sleep(5)
lastRun = time.time()
self.log.debug(_('Fetching tweets for channel %s') % channel)
api = self._getApi(channel) # Reload it from conf everytime
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
return
retweets = self.registryValue('announce.retweets', channel)
try:
tweets = []
if self.registryValue('announce.timeline', channel):
tweets.extend(fetch(
functools.partial(api.GetFriendsTimeline,
retweets=retweets),
maxIds, 'timeline'))
if self.registryValue('announce.mentions', channel):
tweets.extend(fetch(api.GetReplies,
maxIds, 'mentions'))
for user in self.registryValue('announce.users', channel):
if not user.startswith('@'):
user = '@' + user
tweets.extend(fetch(
functools.partial(api.GetUserTimeline,
screen_name=user[1:]),
maxIds, user))
except twitter.TwitterError as e:
self.log.error('Could not fetch timeline: %s' % e)
continue
if not tweets:
continue
tweets.sort(key=operator.attrgetter('id'))
format_ = '@%(user)s> %(msg)s'
if self.registryValue('announce.withid', channel):
format_ = '[%(longid)s] ' + format_
if self.registryValue('announce.withshortid', channel):
format_ = '(%(shortid)s) ' + format_
replies = [format_ % {'longid': x.id,
'shortid': self._get_shortid(x.id),
'user': x.user.screen_name,
'msg': x.text
} for x in tweets]
replies = map(self._unescape, replies)
replies = map(expandLinks, replies)
if self.registryValue('announce.oneline', channel):
irc.replies(replies, prefixNick=False, joiner=' | ',
to=channel)
else:
for reply in replies:
irc.reply(reply, prefixNick=False, to=channel)
finally:
assert channel in self._runningAnnounces
self._runningAnnounces.remove(channel)
@internationalizeDocstring
def following(self, irc, msg, args, channel, user):
"""[<channel>] [<user>]
Replies with the people this <user> follows. If <user> is not given, it
defaults to the <channel>'s account. If <channel> is not given, it
defaults to the current channel."""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer and user is None:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel, or provide '
'a user name.'))
return
following = api.GetFriends(user) # If user is not given, it defaults
# to None, and giving None to
# GetFriends() has the expected
# behaviour.
reply = utils.str.format("%L", ['%s (%s)' % (x.name, x.screen_name)
for x in following])
reply = self._unescape(reply)
irc.reply(reply)
following = wrap(following, ['channel',
optional('somethingWithoutSpaces')])
@internationalizeDocstring
def followers(self, irc, msg, args, channel):
"""[<channel>]
Replies with the people that follow this account. If <channel> is not
given, it defaults to the current channel."""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel, or provide '
'a user name.'))
return
followers = api.GetFollowers()
reply = utils.str.format("%L", ['%s (%s)' % (x.name, x.screen_name)
for x in followers])
reply = self._unescape(reply)
irc.reply(reply)
followers = wrap(followers, ['channel'])
@internationalizeDocstring
def dm(self, irc, msg, args, channel, recipient, message):
"""[<channel>] <recipient> <message>
Sends a <message> to <recipient> from the account associated with the
given <channel>. If <channel> is not given, it defaults to the current
channel."""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op or try with another channel.'))
return
if len(message) > 140:
irc.error(_('Sorry, your message exceeds 140 characters (%i)') %
len(message))
else:
api.PostDirectMessage(recipient, message)
irc.replySuccess()
dm = wrap(dm, [('checkChannelCapability', 'twitteradmin'),
'somethingWithoutSpaces', 'text'])
@internationalizeDocstring
def post(self, irc, msg, args, channel, message):
"""[<channel>] <message>
Posts message to twitter + diaspora"""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op or try with another channel.'))
return
tweet = message
if channel == '#demo':
tweet=str(time.localtime().tm_hour).zfill(2) + str(time.localtime().tm_min).zfill(2) + ' ' + tweet + ' ' + irc.state.channels[channel].topic
if len(tweet) > 300:
irc.error(_('Sorry, your tweet exceeds 300 characters (%i)') %
len(tweet))
else:
api.PostUpdate(tweet)
irc.replySuccess()
post = wrap(post, [('checkChannelCapability', 'twitterpost'), 'text'])
def postt(self, irc, msg, args, channel, message):
"""[<channel>] <message>
Posts message to twitter account only!"""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op or try with another channel.'))
return
tweet = message
if len(tweet) > 300:
irc.error(_('Sorry, your tweet exceeds 300 characters (%i)') %
len(tweet))
else:
api.PostUpdate(tweet)
irc.replySuccess()
postt = wrap(postt, [('checkChannelCapability', 'twitterpost'), 'text'])
def postm(self, irc, msg, args, channel, message):
"""[<channel>] <message> <media_url>
Posts message to twitter account only with attached media"""
api = self._getApi(channel)
id = []
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op or try with another channel.'))
return
pattern = r'(http\S+)'
regex = re.compile(pattern, re.IGNORECASE)
for match in regex.finditer(message):
id.append(api.PostMedia(match.group(1)))
tweet=re.sub(pattern,'',message).strip()
api.PostUpdate(tweet,None,','.join(id))
irc.replySuccess()
postm = wrap(postm, [('checkChannelCapability', 'twitterpost'), 'text'])
def postd(self, irc, msg, args, channel, message):
"""[<channel>] <message>
Posts message to diaspora account only!"""
irc.replySuccess()
postd = wrap(postd, [('checkChannelCapability', 'twitterpost'), 'text'])
@internationalizeDocstring
def reply(self, irc, msg, args, channel, message):
"""[<channel>] <id> <message>
Replies to the status with the given ID. Message must contain @username, where username is the author of the referenced tweet.
If <channel> is not given, it defaults to the
current channel."""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op or try with another channel.'))
return
try:
if message.split(' ',1)[0].isdigit():
id_ = message.split(' ',1)[0]
tweet = message.split(' ',1)[1]
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api.PostUpdate(tweet, id_)
else:
id_ = message.split(' ',1)[0]
tweet = message.split(' ',1)[1]
regex = re.compile("(?:https://)(?:[mobile.]*)(?:twitter.com/)([^//]*)(?:/status/)(\d*)")
r = regex.match(id_)
id_ = r.groups(1)[1]
username = r.groups(1)[0]
api.PostUpdate('@' + username + ' ' + tweet, id_)
irc.replySuccess()
except twitter.TwitterError as e:
irc.error(str(e.args[0]))
reply = wrap(reply, [('checkChannelCapability', 'twitterpost'), 'text'])
@internationalizeDocstring
def rt(self, irc, msg, args, channel, id_):
"""[<channel>] <id>
Retweets the message with the given ID."""
api = self._getApi(channel)
if not id_.isdigit():
regex = re.compile("(?:https://)(?:[mobile.]*)(?:twitter.com/)([^//]*)(?:/status/)(\d*)")
r = regex.match(id_)
id_ = r.groups(1)[1]
try:
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api.PostRetweet(id_)
irc.replySuccess()
except twitter.TwitterError as e:
irc.error(str(e.args[0]))
rt = wrap(rt, [('checkChannelCapability', 'twitterpost'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def fav(self, irc, msg, args, channel, id_):
"""[<channel>] <id>
Favorites the message with the given ID."""
api = self._getApi(channel)
if not id_.isdigit():
regex = re.compile("(?:https://)(?:[mobile.]*)(?:twitter.com/)([^//]*)(?:/status/)(\d*)")
r = regex.match(id_)
id_ = r.groups(1)[1]
try:
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api.CreateFavorite(api.GetStatus(id_))
irc.replySuccess()
except twitter.TwitterError as e:
irc.error(str(e.args[0]))
fav = wrap(fav, [('checkChannelCapability', 'twitterpost'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def defav(self, irc, msg, args, channel, id_):
"""[<channel>] <id>
Favorites the message with the given ID."""
api = self._getApi(channel)
if not id_.isdigit():
regex = re.compile("(?:https://)(?:[mobile.]*)(?:twitter.com/)([^//]*)(?:/status/)(\d*)")
r = regex.match(id_)
id_ = r.groups(1)[1]
try:
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api.DestroyFavorite(api.GetStatus(id_))
irc.replySuccess()
except twitter.TwitterError as e:
irc.error(str(e.args[0]))
defav = wrap(defav, [('checkChannelCapability', 'twitterpost'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def timeline(self, irc, msg, args, channel, tupleOptlist, user):
"""[<channel>] [--since <oldest>] [--max <newest>] [--count <number>] \
[--noretweet] [--with-id] [<user>]
Replies with the timeline of the <user>.
If <user> is not given, it defaults to the account associated with the
<channel>.
If <channel> is not given, it defaults to the current channel.
If given, --since and --max take tweet IDs, used as boundaries.
If given, --count takes an integer, that stands for the number of
tweets to display.
If --noretweet is given, only native user's tweet will be displayed.
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
for key in ('since', 'max', 'count'):
if key not in optlist:
optlist[key] = None
optlist['noretweet'] = 'noretweet' in optlist
optlist['with-id'] = 'with-id' in optlist
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer and user is None:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel.'))
return
try:
timeline = api.GetUserTimeline(screen_name=user,
since_id=optlist['since'],
max_id=optlist['max'],
count=optlist['count'],
include_rts=not optlist['noretweet'])
except twitter.TwitterError:
irc.error(_('This user protects his tweets; you need to fetch '
'them from a channel whose associated account can '
'fetch this timeline.'))
return
if optlist['with-id']:
reply = ' | '.join(['[%s] %s' % (x.id, expandLinks(x.text))
for x in timeline])
else:
reply = ' | '.join([expandLinks(x.text) for x in timeline])
reply = self._unescape(reply)
irc.reply(reply)
timeline = wrap(timeline, ['channel',
getopts({'since': 'int',
'max': 'int',
'count': 'int',
'noretweet': '',
'with-id': ''}),
optional('somethingWithoutSpaces')])
@internationalizeDocstring
def public(self, irc, msg, args, channel, tupleOptlist):
"""[<channel>] [--since <oldest>]
Replies with the public timeline.
If <channel> is not given, it defaults to the current channel.
If given, --since takes a tweet ID, used as a boundary
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
if 'since' not in optlist:
optlist['since'] = None
api = self._getApi(channel)
try:
public = api.GetPublicTimeline(since_id=optlist['since'])
except twitter.TwitterError:
irc.error(_('No tweets'))
return
reply = ' | '.join([expandLinks(x.text) for x in public])
reply = self._unescape(reply)
irc.reply(reply)
public = wrap(public, ['channel', getopts({'since': 'int'})])
@internationalizeDocstring
def getdm(self, irc, msg, args, channel, tupleOptlist):
"""[<channel>] [--count <int>]
Replies with the recieved DMs.
If <channel> is not given, it defaults to the current channel.
If given, --count specifies number of returned DMs
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
if 'count' not in optlist:
optlist['count'] = 5
api = self._getApi(channel)
try:
getdm = api.GetDirectMessages(since=None, since_id=None,count=optlist['count'])
except twitter.TwitterError:
irc.error(_('No tweets'))
return
for x in getdm:
reply = x.created_at + ' ' + x.sender_screen_name + ': ' + expandLinks(x.text)
reply = self._unescape(reply)
irc.reply(reply)
getdm = wrap(getdm, ['channel', getopts({'count': 'int'})])
@internationalizeDocstring
def getsentdm(self, irc, msg, args, channel, tupleOptlist):
"""[<channel>] [--count <int>]
Replies with the recieved DMs.
If <channel> is not given, it defaults to the current channel.
If given, --count specifies number of returned DMs
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
if 'count' not in optlist:
optlist['count'] = 5
api = self._getApi(channel)
try:
getsentdm = api.GetSentDirectMessages(since=None, since_id=None,count=optlist['count'])
except twitter.TwitterError:
irc.error(_('No tweets'))
return
for x in getsentdm:
reply = x.created_at + ' ' + x.recipient_screen_name + ': ' + expandLinks(x.text)
reply = self._unescape(reply)
irc.reply(reply)
getsentdm = wrap(getsentdm, ['channel', getopts({'count': 'int'})])
@internationalizeDocstring
def mentions(self, irc, msg, args, channel, tupleOptlist):
"""[<channel>] [--count <int>]
Get mentions.
If <channel> is not given, it defaults to the current channel.
If given, --count specifies number of returned mentions
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
if 'count' not in optlist:
optlist['count'] = 5
api = self._getApi(channel)
try:
mentions = api.GetMentions(since_id=None, max_id=None,count=optlist['count'])
except twitter.TwitterError:
irc.error(_('No tweets'))
return
for x in mentions:
reply = x.created_at + ' ' + x.user.screen_name + ': ' + expandLinks(x.text)
reply = self._unescape(reply)
irc.reply(reply)
mentions = wrap(mentions, ['channel', getopts({'count': 'int'})])
@internationalizeDocstring
def replies(self, irc, msg, args, channel, tupleOptlist):
"""[<channel>] [--since <oldest>]
Replies with the replies timeline.
If <channel> is not given, it defaults to the current channel.
If given, --since takes a tweet ID, used as a boundary
"""
optlist = {}
for key, value in tupleOptlist:
optlist.update({key: value})
if 'since' not in optlist:
optlist['since'] = None
id_ = optlist['since'] or '0000'
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api = self._getApi(channel)
try:
replies = api.GetReplies(since_id=id_)
except twitter.TwitterError:
irc.error(_('No tweets'))
return
reply = ' | '.join(["%s: %s" % (x.user.screen_name, expandLinks(x.text))
for x in replies])
reply = self._unescape(reply)
irc.reply(reply)
replies = wrap(replies, ['channel',
getopts({'since': 'somethingWithoutSpaces'})])
@internationalizeDocstring
def trends(self, irc, msg, args):
"""[<channel>]
Current trending topics
If <channel> is not given, it defaults to the current channel.
"""
api = self._getApi(channel)
try:
trends = api.GetTrendsCurrent()
except twitter.TwitterError:
irc.error(_('No tweets'))
return
reply = self._unescape(reply)
irc.reply(reply)
trends = wrap(trends)
@internationalizeDocstring
def follow(self, irc, msg, args, channel, user):
"""[<channel>] <user>
Follow a specified <user>
If <channel> is not given, it defaults to the current channel.
"""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel.'))
return
try:
follow = api.CreateFriendship(user)
except twitter.TwitterError:
irc.error(_('An error occurred'))
return
irc.replySuccess()
follow = wrap(follow, ['channel', ('checkChannelCapability', 'twitteradmin'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def unfollow(self, irc, msg, args, channel, user):
"""[<channel>] <user>
Unfollow a specified <user>
If <channel> is not given, it defaults to the current channel.
"""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel.'))
return
try:
unfollow = api.DestroyFriendship(user)
except twitter.TwitterError:
irc.error(_('An error occurred'))
return
irc.replySuccess()
unfollow = wrap(unfollow, ['channel',
('checkChannelCapability', 'twitteradmin'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def delete(self, irc, msg, args, channel, id_):
"""[<channel>] <id>
Delete a specified status with id <id>
If <channel> is not given, it defaults to the current channel.
"""
if len(id_) <= 3:
try:
id_ = self._shortids[id_]
except KeyError:
irc.error(_('This is not a valid ID.'))
return
else:
try:
id_ = int(id_)
except ValueError:
irc.error(_('This is not a valid ID.'))
return
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel.'))
return
try:
delete = api.DestroyStatus(id_)
except twitter.TwitterError:
irc.error(_('An error occurred'))
return
irc.replySuccess()
delete = wrap(delete, ['channel',
('checkChannelCapability', 'twitteradmin'),
'somethingWithoutSpaces'])
@internationalizeDocstring
def twitstats(self, irc, msg, args, channel):
"""[<channel>]
Print some stats
If <channel> is not given, it defaults to the current channel.
"""
api = self._getApi(channel)
try:
reply = {}
reply['followers'] = len(api.GetFollowers())
reply['following'] = len(api.GetFriends(None))
except twitter.TwitterError:
irc.error(_('An error occurred'))
return
reply = "I am following %d people and have %d followers" % (reply['following'], reply['followers'])
irc.reply(reply)
twitstats = wrap(twitstats, ['channel'])
@internationalizeDocstring
def profile(self, irc, msg, args, channel, user=None):
"""[<channel>] [<user>]
Return profile image for a specified <user>
If <channel> is not given, it defaults to the current channel.
"""
api = self._getApi(channel)
if hasattr(api, '_oauth_consumer') and not api._oauth_consumer:
irc.error(_('No account is associated with this channel. Ask '
'an op, try with another channel.'))
return
try:
if user:
profile = api.GetUser(user)
else:
profile = api.VerifyCredentials()
except twitter.TwitterError:
irc.error(_('An error occurred'))
return
irc.reply(('Name: @%s (%s). Profile picture: %s. Biography: %s') %
(profile.screen_name,
profile.name,
profile.GetProfileImageUrl().replace('_normal', ''),
profile.description))
profile = wrap(profile, ['channel', optional('somethingWithoutSpaces')])
def die(self):
self.__parent.die()
self._died = True
Class = Twitter
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: