-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
289 lines (205 loc) · 10 KB
/
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
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
#/usr/bin/env python3
# bot.py
#TODO: Spend points?
import cfg
import logging
import os
import re
import requests
import shelve
import socket
import sys
import threading
from time import sleep
from datetime import datetime, timedelta
from urllib.parse import quote
#regex, pulls chat from twitch irc 'response'.
chat_msg=re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
#regex, tries to extract an urbandictionary word's definition.
#definition_regex = r'.definition.\:(.+?)(permalink.\:|author.\: ..|current_vot|thumbs_up.\:|thumbs_down|example.\:..|word.\:.....|defid.\:....)'
def chat(sock, msg):
sock.send(bytes("PRIVMSG {} :{} \r\n".format(cfg.CHAN, msg), 'utf-8'))
def urban(word):
word_in_ascii = quote(word)
built_url = 'https://api.urbandictionary.com/v0/define?term=' + word_in_ascii
r = requests.get(built_url)
if len(r.json()['list']) > 0:
top_definition = r.json()['list'][0]['definition']
top_definition = re.sub(r'\r', ' ', top_definition)
top_definition = re.sub(r'\n', ' ', top_definition)
top_definition = re.sub(r' ', ' ', top_definition)
bot_says = word + '- ' + top_definition
if len(bot_says) >= 500:
bot_says = bot_says[:499]
return bot_says
else:
bot_says = word + ' is undefined!'
return bot_says
def chatbot():
while True:
response = irc.recv(1204).decode('utf-8')
username = re.search(r"\w+", response).group(0)
message = chat_msg.sub("", response)
message = message.rstrip()
#logging.debug(' '+ username + ": " + message)
if response == "PING :tmi.twitch.tv\r\n":
irc.send(bytes("PONG :tmi.twitch.tv\r\n", 'utf-8'))
else:
if re.match(r'^!urban', message):
bot_says = "i'm confused.. what did you ask?"
if (message == '!urban') or (message == '!urban '):
bot_says = "!urban - defines a word using urban dictionary."
else:
search_term = message[7:]
bot_says = urban(search_term)
chat(irc, bot_says)
elif re.match(r'^!echo', message):
bot_says = message[6:]
chat(irc, bot_says)
elif re.match(r'^!commands', message):
bot_says = 'commands: !urban word - gives the urban ' \
+ 'definition of a word (if it exists). '\
+ '!points help - commands for !points. '
chat(irc, bot_says)
elif re.match(r'^!bots', message):
bot_says = 'MrDestructoid'
chat(irc, bot_says)
elif re.match(r'^!points', message):
if (message == '!points') or (message == '!points '):
with shelve.open(os.path.join(sys.path[0],cfg.CHAN[1:])) as s:
if username in s:
user_points = str(s[username])
bot_says = '@' + username + ' has ' \
+ user_points \
+ ' points.'
else:
bot_says = ('@' + username \
+ ' you got no points, '\
+ 'watch more stream bruh.')
chat(irc, bot_says)
elif message == '!points help':
bot_says = '@' + username + ' :' + '!points commands: ' \
+ "'!points', '!points claim' " \
+ "'!points top'. points cannot be earned while"\
+ " streamer is offline."
chat(irc, bot_says)
elif message == '!points claim':
redeemed_filename = cfg.CHAN[1:] + 'REDEEMED'
current_users = requests.get(\
'https://tmi.twitch.tv/group/user/'\
+ cfg.CHAN[1:] + '/chatters')
current_users = current_users.json()
current_users = current_users['chatters']['moderators']\
+ current_users['chatters']['viewers']
if cfg.CHAN[1:] in current_users:
with shelve.open(os.path.join(sys.path[0],redeemed_filename)) as redeemed:
if username in redeemed:
bot_says = '@'+username+' you may only claim '\
+ 'points once per stream.'
else:
with shelve.open(os.path.join(sys.path[0],cfg.CHAN[1:])) as s:
if username in s:
s[username] += 100
bot_says = '@'+username+' claimed 100'\
+ ' points. new_total: '\
+ str(s[username])
else:
s[username] = 100
bot_says = '@'+username+' claimed 100'\
+ ' points. new_total: '\
+ str(s[username])
redeemed[username] = 1
else:
bot_says = cfg.CHAN[1:] + ' must be online to claim,'\
+ ' check back later.'
chat(irc, bot_says)
elif message == '!points top':
try:
with shelve.open(os.path.join(sys.path[0],cfg.CHAN[1:])) as s:
score_tups = sorted(s.items(), key=lambda x: \
x[1])[::-1]
top_five = score_tups[:5]
bot_says = '!points high scores: ' \
+'First: '+top_five[0][0]+' ('+str(top_five[0][1])+') '\
+'Second: '+top_five[1][0]+' ('+str(top_five[1][1])+') '\
+'Third: '+top_five[2][0]+' ('+str(top_five[2][1])+') '\
+'Fourth: '+top_five[3][0]+' ('+str(top_five[3][1])+') '\
+'Fifth: '+top_five[4][0]+' ('+str(top_five[4][1])+')'
chat(irc, bot_says)
except:
bot_says = 'need more viewers to have a top 5.'
chat(irc, bot_says)
elif message == '!points redeem':
bot_says = 'what to do with points. gamble?'\
+ 'buy mod with 1M points? Kappa '
chat(irc, bot_says)
sleep(1 / cfg.RATE)
def add_points(current_users):
streamer_online = False
timestamped = False # find a way to check if timestamped
while True:
current_users_dict = {user:0 for user in current_users}
sleep(60)
new_users = requests.get('https://tmi.twitch.tv/group/user/'\
+ cfg.CHAN[1:] + '/chatters')
new_users = new_users.json()
new_users = new_users['chatters']['moderators']\
+ new_users['chatters']['viewers']
if cfg.CHAN[1:] in current_users:
streamer_online = True
for user in current_users:
if user in new_users:
current_users_dict[user] += 1
timestamped = False
with shelve.open(os.path.join(sys.path[0],cfg.CHAN[1:])) as s:
for user in current_users_dict:
if user not in cfg.NO_POINTS:
if user in s:
s[user] += 1
else:
s[user] = 1
if cfg.CHAN[1:] not in new_users:
logging.debug('streamer disconnected.')
elif cfg.CHAN[1:] in new_users:
streamer_online = True
logging.debug('streamer online!')
timestamped = False
else: #streamer not in new users or current users (offline)
streamer_online = False
logging.debug('streamer offline.')
if (streamer_online == False) and (timestamped == False):
offline_time = datetime.now()
timestamped = True
logging.debug('offline_time set, '\
+'REDEEMED flagged for deletion.')
between_streams = timedelta(hours=4)
reset_claim = offline_time + between_streams
if datetime.now() > reset_claim:
try:
os.remove(os.path.join(sys.path[0], (cfg.CHAN[1:]\
+'REDEEMED.db')))
logging.debug('file removed, users may redeem again.')
except:
logging.debug(' could not remove "redeemed, "'\
+ 'file not found?')
timestamped = False
current_users = new_users
logging.basicConfig(filename=(os.path.join(sys.path[0], cfg.CHAN[1:]\
+'LOG.log')),level=logging.DEBUG)
irc = socket.socket()
irc.connect((cfg.HOST, cfg.PORT))
irc.send(bytes("PASS {}\r\n".format(cfg.PASS), 'utf-8'))
irc.send(bytes("NICK {}\r\n".format(cfg.NICK), 'utf-8'))
irc.send(bytes("JOIN {}\r\n".format(cfg.CHAN), 'utf-8'))
login_users = requests.get('https://tmi.twitch.tv/group/user/'\
+ cfg.CHAN[1:] + '/chatters')
login_users = login_users.json()
login_users = login_users['chatters']['moderators']\
+ login_users['chatters']['viewers']
logging.debug('Connected to '+cfg.CHAN[1:]+' with'+str(len(login_users))\
+'users watching now.')
chat_loop = threading.Thread(name='chatbot', target=chatbot)
point_loop = threading.Thread(name='add_points', target=add_points,\
args=[login_users])
chat_loop.start()
point_loop.start()