class TwitchChatInputView(view.View): """Class for handling Twitch chat input.""" def __init__(self): super().__init__() self.observer = None pubsub.subscribe('QUIT', self.on_quit) def on_quit(self): self._running = False def init(self): working_dir = os.path.dirname(__file__) config_path = os.path.normpath( os.path.join(working_dir, './config.cfg')) if not os.path.exists(config_path): raise RuntimeError('Missing Twitch chatbot config.cfg file') # Import Twitch bot settings config = configparser.ConfigParser() config.read(config_path) nickname = config['TWITCH']['Nickname'] password = config['TWITCH']['Password'] channel = config['TWITCH']['Channel'] self.observer = Observer(nickname, password) self.observer.start() self.observer.join_channel(channel) def deinit(self): self.observer.stop() def update(self, time): for event in self.observer.get_events(): if event.type == 'TWITCHCHATMESSAGE': move = event.message # Filter Twitch chat input if re.match('[a-h][1-8][a-h][1-8]', move): move = move.lower() player_name = event.nickname player_color = event.tags['color'] if not player_color: player_color = '#FFFFFF' hex_color = player_color.strip('#') r = int(hex_color[0:2], 16) g = int(hex_color[2:4], 16) b = int(hex_color[4:6], 16) player_color = r, g, b self.send_move(move, player_name, player_color)
class Game(object): args = None scene_root = None config = None instance = None tick_count = 0 seconds_per_tick = 0 def __init__(self, args): Game.args = args # Configure game settings config = configparser.ConfigParser() cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.cfg') config.read(cfg_path) Game.config = config # Configure tdl tdl.set_font(Game.config['ENGINE']['font']) tdl.set_fps(int(Game.config['ENGINE']['fps'])) self.console = tdl.init(54, 30, 'lunch break roguelike', renderer=Game.config['ENGINE']['renderer']) self._last_time = time.time() Game.seconds_per_tick = float(Game.config['GAME']['turn']) if not Game.instance: Game.instance = self instances.register('game', self) # Twitch Observer nickname = Game.config['TWITCH']['Nickname'] password = Game.config['TWITCH']['Password'] self.channel = Game.config['TWITCH']['Channel'] self.observer = Observer(nickname, password) self.observer.start() self.observer.join_channel(self.channel) self.start_time = time.time() Game.scene_root = gamescene.GameScene() @property def time_since_start(self): return time.time() - self.start_time def run(self): timer = 0 last_time = 0 running = True self.start_time = time.time() while running: # Draw the scene self.console.clear() Game.scene_root.draw(self.console) tdl.flush() # Handle input/events for event in list(tdl.event.get()) + self.observer.get_events(): Game.scene_root.handle_events(event) if event.type == 'QUIT': running = False self.observer.stop() # Update scene time_elapsed = time.time() - last_time timer += time_elapsed last_time = time.time() Game.scene_root.update(time_elapsed) # Send out tick event if timer > Game.seconds_per_tick: timer = 0 Game.tick_count += 1 Game.scene_root.tick(Game.tick_count)
print("connecting") observer = Observer(USER, AUTHKEY) with observer: print("joining C 1") observer.join_channel(CHANNEL_1) print("running in C 1") print("joining C 2") observer.join_channel(CHANNEL_2) print("running in C 2") print("running") try: while True: e = observer.get_events() if (len(e) > 0): print("got %i events" % len(e)) for event in e: if (hasattr(event, "tags")): if (event.tags.get("id")): print("ID is %s %s " % (event.tags.get("id"), seenBefore)) if (event.tags.get("id") in seenBefore): # duplicate message continue else: seenBefore.add(event.tags.get("id")) print(event) if event.type == 'TWITCHCHATMESSAGE':
monster = Entity(0, 2, 2, 'k', (255, 0, 0)) items = [] entities = [] tnames = [] evnt_handler = events.Event_Handler(player) hx = 0 hy = 0 running = True while running: console.clear(fg=(255, 0, 0)) renderer.render(console, entities, items, levelmap, SCREEN_WIDTH, SCREEN_HEIGHT) renderer.draw_entity(0, player) evnt_handler.handle_event() for event in observer.get_events(): print(len(twitch_names), twitch_names) if event.type == 'TWITCHCHATMESSAGE': if event.nickname not in twitch_names: if max_monsters < 10: twitch_names.append(event.nickname) for n in twitch_names: tnames.append(n) while levelmap.is_solid(hx, hy) and twitch_names: hx = randint(1, MAP_WIDTH - 1) hy = randint(1, MAP_HEIGHT - 1) if not levelmap.is_solid(hx, hy): name = event.nickname entities.append( Entity(0, hx, hy, name[:1].lower(), ((randint(100, 255), randint(
def main(): # Networking functions, joins channel and sends a message, retrieves modlist # To do: # add custom commands obs = Observer(cfg.NICK, cfg.PASS) obs.start() obs.join_channel(cfg.CHAN) #obs.send_message("Hi everyone <3", cfg.CHAN) obs.send_message("/mods", cfg.CHAN) def get_votes(): if event.type == 'TWITCHCHATMESSAGE': votes = {} votes.clear() timeout = 70 timeout_start = time.time() while time.time() < timeout_start + timeout: time.sleep(0.25) try: if event.message in str(voteOptions): votes[event.nickname] = event.message except: 'do nothing' c = Counter(votes.values()) c = str(c) c = c.split('{') c = c[1] c = c.split('}') c = c[0] c = str(c) results = c.split(',') for result in results: i = result.split(':') message = 'the result of option ' + i[ 0] + ' is a total of ' + i[1] + ' votes' botmsg(message) obs.send_message(message, cfg.CHAN) #botmsg('The results of the voting is: ' + str(message)) print(votes) print(c) ######################################################################## ############ Log, Modlist, Caps Filter while True: for event in obs.get_events(): # print Messages in Terminal # for Debugging reasons if event.type == 'TWITCHCHATMESSAGE': print(event.nickname, ": ", event.message) # get modlist # gets a list of all mods of the channel # and saves them in modlist if event.type == 'TWITCHCHATNOTICE' and "The moderators of this channel are:" in event.message: modlist = event.message.split(":") modlist = modlist[1] # to Do get active list username + ID # create active viewerlist if event.type == 'TWITCHCHATUSERSTATE': activeViewer = {} name = str(event._params) name = name.split('#') name = name[1] client = TwitchClient(cfg.ClientID) try: nameid = client.users.translate_usernames_to_ids(name) except: continue nameid = str(nameid) nameid = nameid.split(",") nameid = nameid[1] nameid = nameid.split(":") nameid = nameid[1] nameid = nameid.split("'") nameid = nameid[1] activeViewer[name] = nameid activeViewer.setdefault(name, nameid) # delete user from list if they leave if event.type == 'TWITCHCHATLEAVE': name = str(event.nickname) try: del activeViewer[name] except: 'do nothing' ######################################################################## ####### Kuu commands # Hype if event.type == 'TWITCHCHATMESSAGE' and event.message == "!hype" and event.nickname == 'chris_lee_bear': message = "sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd " obs.send_message(message, cfg.CHAN) botmsg(message) # Bye if event.type == 'TWITCHCHATMESSAGE' and "say goodbye bot" in event.message and event.nickname == 'chris_lee_bear': message = "master said I have to say goodbye... see you soon everyone <3" obs.send_message(message, cfg.CHAN) botmsg(message) #Sub notice if event.type == 'TWITCHCHATNOTICE' and "subscribed" in event.message: message1 = "Thanks for the Sub <3" message2 = "sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd sunbroLewd " obs.send_message(message1, cfg.CHAN) obs.send_message(message2, cfg.CHAN) botmsg(message1) botmsg(message2) # Voting if event.type == 'TWITCHCHATMESSAGE': if "!voting" in event.message and ( event.nickname in modlist or event.nickname == 'chris_lee_bear' or event.nickname == cfg.CHAN): try: voteOptions = [] message = event.message.split(' ') message = message[1] message = int(message) + 1 voteOptions = list(range(message)) del voteOptions[0] print(voteOptions) #obs.send_message('Voting will be open for 60 seconds. To voty simply type the number in chat you want to vote for. The options are '+ str(voteOptions), cfg.CHAN) #time.sleep(1) t = threading.Thread(target=get_votes) t.daemon = True t.start() except: print('do nothing') if event.type == 'TWITCHCHATMESSAGE' and event.message == '!voteinfo': message = ( 'If voting is enabled, to vote simply type the number in chat you want to vote for and remember you can change your vote but only the last vote will be counted' ) botmsg(message) obs.send_message(message, cfg.CHAN) ############# Custom Commands # Kappa Command also known as test command if event.type == 'TWITCHCHATMESSAGE' and event.message == "!Kappa": user = str(event.nickname) message = "@" + user + " Kappa" obs.send_message(message, cfg.CHAN) botmsg(message) # Shoutout if event.type == 'TWITCHCHATMESSAGE' and "!so" in event.message and ( event.nickname in modlist or event.nickname == cfg.CHAN): try: b = event.message.split(" ") b = b[1] b = str(b) message = "please check out this awesome person @" + b + " at: https://www.twitch.tv/" + b obs.send_message(message, cfg.CHAN) botmsg(message) except: continue # mod list test if event.type == 'TWITCHCHATMESSAGE' and event.message == "!mod": message = "the awesome people that help me doing my thing :" + modlist obs.send_message(message, cfg.CHAN) botmsg(message) # User ID test if event.type == 'TWITCHCHATMESSAGE' and event.message == "!user": client = TwitchClient(cfg.ClientID) message = client.users.translate_usernames_to_ids( event.nickname) message = str(message) message = message.split(",") message = message[1] message = message.split(":") message = message[1] message = message.split("'") message = message[1] obs.send_message(message, cfg.CHAN) botmsg(message) if event.type == 'TWITCHCHATMESSAGE' and event.message == "!list": message = str(activeViewer[name]) obs.send_message(message, cfg.CHAN) botmsg(message) #### sql part #fill_viewer_list if event.type == 'TWITCHCHATMESSAGE': client = TwitchClient(cfg.ClientID) try: conn = db.connect(dbname=cfg.DBname, user=cfg.DBuser, password=cfg.DBpassword, host=cfg.DBhost, port=cfg.DBport) conn.autocommit = True viewer = str(event.nickname) viewerID = client.users.translate_usernames_to_ids( event.nickname) viewerID = str(viewerID) viewerID = viewerID.split(",") viewerID = viewerID[1] viewerID = viewerID.split(":") viewerID = viewerID[1] viewerID = viewerID.split("'") viewerID = int(viewerID[1]) joindate = str(time.strftime("%Y.%m.%d")) points = int(0) # insert data in table cursor = conn.cursor() query = """INSERT INTO {0}.viewerlist ( viewer, viewerID, joindate, points ) Values( %(viewer)s, %(viewerID)s, %(joindate)s, %(points)s ) on CONFLICT (viewerID) DO NOTHING """.format(cfg.CHAN) cursor.execute( query, { 'viewer': viewer, 'viewerID': viewerID, 'joindate': joindate, 'points': points }) cursor.close() conn.close except: print("fill list error") ### add points sql.addPoints(cfg.CHAN, activeViewer[name])