· 6 years ago · Feb 21, 2019, 05:56 AM
1import sys
2import irc.bot
3import requests
4import random
5import json
6from threading import Thread
7import time
8import nouns
9import re
10
11class TwitchBot(irc.bot.SingleServerIRCBot):
12
13 def is_live_stream(self,channel):
14
15 url = 'https://api.twitch.tv/kraken/streams/' + channel
16 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
17 data = requests.get(url, headers=headers).json()
18 print(json.dumps(data, indent=4, sort_keys=True))
19 try:
20 streamID = data['stream']['_id']
21 except:
22 streamID = -1
23 return int(streamID)
24
25 def poll(self):
26 c = self.connection
27 while(1):
28 poll = self.is_live_stream(self.channel_id)
29 print(poll,end="", flush=True)
30 if (poll != -1):
31 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
32 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
33 r = requests.get(url, headers=headers).json()
34 c.privmsg(self.channel, r['display_name'] + ' is live!')
35 print('XX> noahisbot: '+ r['display_name'] + ' is live!')
36 break
37 time.sleep(3)
38 return
39
40 def hydrate(self):
41 c = self.connection
42 while(1):
43 poll = self.is_live_stream(self.channel_id)
44 if (poll == -1):
45 break
46 time.sleep(1800)
47 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
48 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
49 r = requests.get(url, headers=headers).json()
50 c.privmsg(self.channel,r['display_name'] + ' time to hydrate! DrinkPurple')
51
52 def __init__(self, username, client_id, token, channel):
53 self.client_id = client_id
54 self.token = token
55 self.channel = '#' + channel
56 self.countdown = random.randint(20,50)
57 self.nouns = nouns.nouns
58
59 # Get the channel id, we will need this for v5 API calls
60 url = 'https://api.twitch.tv/kraken/users?login=' + channel
61 headers = {'Client-ID': client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
62 r = requests.get(url, headers=headers).json()
63 self.channel_id = r['users'][0]['_id']
64
65 # Create IRC bot connection
66 server = 'irc.chat.twitch.tv'
67 port = 6667
68 print ('Connecting to ' + server + ' on port ' + str(port) + '...')
69 irc.bot.SingleServerIRCBot.__init__(self, [(server, port, 'oauth:'+token)], username, username)
70
71 hydrate = Thread(target=self.hydrate)
72 hydrate.start()
73
74 #polling = Thread(target=self.poll)
75 #polling.start()
76 #print ('Polling First')
77
78 def on_welcome(self, c, e):
79 print ('Joining ' + self.channel)
80
81 # You must request specific capabilities before you can use them
82 c.cap('REQ', ':twitch.tv/membership')
83 c.cap('REQ', ':twitch.tv/tags')
84 c.cap('REQ', ':twitch.tv/commands')
85 c.join(self.channel)
86
87 def on_pubmsg(self, c, e):
88 msg = ''
89 for str in e.arguments:
90 msg += str + ' '
91 print (('{}> ' + e.source.split('!')[0] + ': ' + self.BMP(msg)).format(self.countdown))
92 if self.countdown == 0:
93 self.countdown = random.randint(20,50)
94 temp_rand = random.randint(1,100)
95 print(temp_rand)
96 if temp_rand < 2:
97 c.privmsg(self.channel,'thejam1Mask')
98 print('XX> noahisbot: thejam1Mask')
99 elif temp_rand >= 2 and temp_rand <4:
100 c.privmsg(self.channel,'tragic13WhatAtwist')
101 print('XX> noahisbot: tragic13WhatAtwist')
102 else:
103 reply = e.arguments[0]
104 for noun in self.nouns:
105 if re.search(r'\b'+noun+r's?\b', reply, re.IGNORECASE):
106 pattern = re.compile(r'\b'+noun+r's?\b', re.IGNORECASE)
107 reply = pattern.sub('balls', reply)
108 if reply != e.arguments[0]:
109 reply_split = reply.split(' ')
110 random.shuffle(reply_split)
111 reply_shuffled_string = ''
112 for reply_item in reply_split:
113 reply_shuffled_string += reply_item + ' '
114 c.privmsg(self.channel,reply_shuffled_string)
115 print('XX> noahisbot: ' + reply_shuffled_string)
116 else:
117 temp_rand_2 = random.randint(1,100)
118 if temp_rand_2 < 51:
119 c.privmsg(self.channel,'thejam1Mask')
120 print('XX> noahisbot: thejam1Mask')
121 else:
122 c.privmsg(self.channel,'tragic13WhatAtwist')
123 print('XX> noahisbot: tragic13WhatAtwist')
124 else:
125 self.countdown -= 1
126
127 # If a chat message starts with an exclamation point, try to run it as a command
128 if e.arguments[0][:1] == '!' and (e.source.split('!')[0] == "noahismad" or e.source.split('!')[0] == "trialorc"):
129 cmd = e.arguments[0].split(' ')[0][1:]
130 print ('Received command: ' + cmd)
131 self.do_command(e, cmd)
132 if e.arguments[0].split(' ')[0] == '!unsub' or e.arguments[0].split(' ')[0] == '!unsubscribe':
133 c.privmsg(self.channel,e.source.split('!')[0] + ' unsubscribed')
134 print('XX> noahisbot:' + e.source.split('!')[0] + ' unsubscribed')
135 #else:
136 #self.echo(e)
137 return
138
139 def echo(self, e):
140 c = self.connection
141 c.privmsg(self.channel, e.source.split('!')[0] + ": " + e.arguments[0])
142
143 def BMP(self, s):
144 return "".join((i if ord(i) < 10000 else '\ufffd' for i in s))
145
146 def do_command(self, e, cmd):
147 c = self.connection
148 if cmd == "sayhi":
149 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
150 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
151 r = requests.get(url, headers=headers).json()
152 c.privmsg(self.channel, 'Hi ' + r['display_name'])
153 print('XX> noahisbot: Hi '+ r['display_name'])
154 elif cmd == "saybye":
155 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
156 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
157 r = requests.get(url, headers=headers).json()
158 c.privmsg(self.channel, 'Bye ' + r['display_name'])
159 print('XX> noahisbot: Bye '+ r['display_name'])
160 elif cmd == "pollfirst":
161 polling = Thread(target=self.poll)
162 polling.start()
163 print ('Polling First')
164 elif cmd == "play":
165 c.privmsg(self.channel,'!play')
166 print('XX> noahisbot: !play')
167 elif cmd == "vote":
168 vote = '!vote ' + str(random.randint(1,42))
169 c.privmsg(self.channel,vote)
170 print('XX> noahisbot: ' + vote)
171 elif cmd == "so":
172 c.privmsg(self.channel,'leave me alone ' + e.source.split('!')[0] + ' do your own promoting')
173 print('XX> noahisbot: leave me alone ' + e.source.split('!')[0] + ' do your own promoting')
174
175 # Poll the API to get current game.
176 elif cmd == "game":
177 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
178 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
179 r = requests.get(url, headers=headers).json()
180 c.privmsg(self.channel, r['display_name'] + ' is currently playing ' + r['game'])
181
182 # Poll the API the get the current status of the stream
183 elif cmd == "title":
184 url = 'https://api.twitch.tv/kraken/channels/' + self.channel_id
185 headers = {'Client-ID': self.client_id, 'Accept': 'application/vnd.twitchtv.v5+json'}
186 r = requests.get(url, headers=headers).json()
187 c.privmsg(self.channel, r['display_name'] + ' channel title is currently ' + r['status'])
188
189 # The command was not recognized
190 #else:
191 #c.privmsg(self.channel, "Did not understand command: " + cmd)
192
193
194
195##I define my stuff here instead of as a run argument
196def main():
197 username = " "
198 client_id = " "
199 token = " "
200 channel = " "
201
202 bot = TwitchBot(username, client_id, token, channel)
203 bot.start()
204
205if __name__ == "__main__":
206 main()