/
irc_twit_bot.py
executable file
·243 lines (200 loc) · 7.11 KB
/
irc_twit_bot.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tweepy
import Queue
import time
import auth
from HTMLParser import HTMLParser
## import logging
import re
from oyoyo.client import IRCClient
from oyoyo.cmdhandler import DefaultCommandHandler
from oyoyo import helpers
##CUSTOMIZE_THIS_START
HOST = 'irc.freenode.net'
PORT = 6667
NICK = 'Jtwitt'
CHANNEL = '#Jeanne_D\'Hack'
WHITELIST = [ "moebius_eye", "Mydym", "skelkey", "sybix", "Vigdis", "xoomed", "y0no", "Lotto", "chiropter", "grab", "Trium" ]
##CUSTOMIZE_THIS_END
def twitt ( nick, chan, to_say ) :
global api
global cli
## Si on a la place d'ajouter une signature, on le fait.
if len(to_say) > 0 and len( "%s -- %s" % (to_say , nick) ) <= 140 :
to_say = "%s -- %s" % (to_say , nick)
## Si le message est à la bonne taille
if 0 < len(to_say) and len(to_say) <= 140 :
## Envoyer le twitt et confirmer sur le canal
try:
api.update_status(to_say)
print('Saying, "%s"' % to_say)
helpers.msg(cli, chan, '>%s > Twitt envoyé' % nick )
return True
except:
helpers.msg(cli, chan, '>%s > Erreur non prévisible. Ooops.' % nick )
## Sinon, signaler l'erreur
elif len(to_say) > 140:
helpers.msg(cli, chan, '>%s > Twitt trop long (%d char)' % ( nick, len(to_say) ) )
elif len(to_say) <= 0:
helpers.msg(cli, chan, '>%s > Syntax: !say <message> | Interdiction d\'envoyer un twitt vide.' % nick )
class StreamWatcherListener(tweepy.StreamListener):
def __init__(self, status_queue):
super( StreamWatcherListener, self ).__init__()
self.status_queue = status_queue
def on_status(self, status):
try:
print 'new tweet'
print status.text
self.status_queue.put(status)
except:
## Catch any unicode errors while printing to console
## and just ignore them to avoid breaking application.
pass
def on_error(self, status_code):
print 'An error has occured! Status code = %s' % status_code
if status_code == '420':
time.sleep(5)
return False
return True # keep stream alive
def on_timeout(self):
print 'Snoozing Zzzzzz'
class MyHandler(DefaultCommandHandler):
def privmsg(self, nick_extended, chan, msg):
global api
global cli
global denied_cmd
global respond_to
## Getting "nick" from "nick!user@domain" string
nick = re.match('(.*)\!', nick_extended).group(1).strip()
## Making sure the user is in the whitelist
match = re.match('\!([a-z]*)(.*)', msg)
if match:
cmd = match.group(1).strip()
to_say = match.group(2).strip()
print cmd, nick, to_say
if match and cmd in ["say","respond"] and nick not in WHITELIST :
match = False
denied_cmd = msg
helpers.msg(cli, chan, u">%s > Vous n\'ètes pas dans la liste blanche. Une whitelisté peut !accept votre commande." % nick )
## Si la commande a été comprise
try:
if match:
if cmd == "say":
twitt( nick, chan, to_say )
elif cmd == "accept":
try:
self.privmsg( nick_extended, chan, denied_cmd )
except:
helpers.msg(cli, chan, u">%s > Rien à accepter " % nick )
elif cmd == "respond":
twitt( nick, chan, "@%s %s" % ( respond_to ,to_say ) )
else:
helpers.msg(cli, chan, u">%s > commandes prises en charge: !say <msg> | !respond <msg> | !accept " % nick)
else:
print "Parsing error"
except:
helpers.msg(cli, chan, u">%s > Erreur lors de l'execution de la commande." % nick )
def kick( self, kickernick, chan, mynick, reason ):
print "kick: %s " % reason
if reason not in ["perma","permanent","perm","flood","flooding"] :
time.sleep(2)
helpers.join(cli, CHANNEL)
def error( self, nick, reason ):
print "error: %s " % reason
try:
time.sleep(2)
helpers.join(cli, CHANNEL)
except:
main()
def quit( self, nick, reason ):
try:
try:
main()
except:
print "ircinit or main failure"
try:
main()
except:
print "\"You get nothing done\" -- Axl' Rose"
pass
except:
print "something went wrong."
helpers.join(cli, CHANNEL)
def connect_cb(cli):
helpers.join(cli, CHANNEL)
def main():
global conn
global respond_to
i = 0
old_id = 0
start = time.time()
while True:
time.sleep(0.5)
if i < 200:
i+=1
if i == 100:
print 'joining'
helpers.join(cli, CHANNEL)
if i == 200:
print 'joining'
helpers.join(cli, CHANNEL)
i+=1
if i > 200:
mentions = []
if time.time() - start > 20 :
start = time.time()
print "getting goodies"
try:
mentions = api.mentions()
mentions = mentions[:1] ## Get only the last mention
except:
mentions = []
pass
mentions.reverse()
for mention in mentions:
if mention.id > old_id :
text = HTMLParser().unescape(mention.text)
helpers.msg(cli, CHANNEL, '@%s nous dis : %s' % \
(mention.author.screen_name , text) )
respond_to = mention.author.screen_name
old_id = mention.id + 1
try:
item = status_queue.get(False)
print str(item.author.screen_name)
if str(item.author.screen_name) != NICK:
helpers.msg(cli, CHANNEL, str(item.author.screen_name)+' -- '+str(item.text))
api.update_status(str(item.author.screen_name)+' -- '+str(item.text))
except KeyboardInterrupt:
print "Interrupted"
exit()
except:
pass
conn.next() ## python 2
def ircinit():
global conn
global cli
## Setting IRC cli.
## logging.basicConfig(level=logging.DEBUG)
cli = IRCClient(MyHandler, host=HOST, port=PORT, nick=NICK)#,connect_cb=connect_cb)
conn = cli.connect()
if __name__ == '__main__':
status_queue = Queue.Queue()
consumer_key = auth.consumer_key
consumer_secret = auth.consumer_secret
key = auth.key
secret = auth.secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
api = tweepy.API(auth)
stream = tweepy.Stream(auth=auth, listener=StreamWatcherListener(status_queue))
## Setting IRC cli.
ircinit()
track_list = []
follow_list = []
stream.filter(follow_list, track_list, True)
try:
main()
except KeyboardInterrupt:
print "Interrupted"
exit()