Skip to content
This repository was archived by the owner on Jul 21, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 95 additions & 63 deletions ChatEventHandler.py
Original file line number Diff line number Diff line change
@@ -1,104 +1,136 @@
''' Handles and formats chat events '''
"""Handles and formats chat events."""
import requests


class Handler():
'''handles chat events'''
"""Handle chat events."""

def __init__(self, config, chat):
self.config = config
self.event_types = {
'reply': self.type_reply, 'event': self.type_event,
'method': self.type_method, 'system': self.type_system}
"reply": self.type_reply, "event": self.type_event,
"method": self.type_method, "system": self.type_system}
self.poll_switch = True
self.chat = chat

def formatting(self, data):
'''
checks the event type and calls the function
relating to that event type
'''
func = self.event_types[data['type']]
"""Check the event type and call the function relating to that type."""
func = self.event_types[data["type"]]
func(data)
if self.config.CHATDEBUG:
print(data)

def type_reply(self, data):
'''Handles the Reply type data'''
if 'data' in data:
if 'authenticated' in data['data']:
if data['data']['authenticated']:
print('Authenticated with the server')
"""Handle the Reply type data."""
if "data" in data:
if "authenticated" in data["data"]:
if data["data"]["authenticated"]:
print("Authenticated with the server")
else:
print('Authenticated Failed, Chat log restricted')
print("Authenticated Failed, Chat log restricted")
else:
print('Server Reply: {}'.format(str(data)))
print(f"Server Reply: {str(data)}")
else:
print('Server Reply: {}'.format(str(data['error'])))
print(f"Server Reply: {str(data['error'])}")

def type_event(self, data):
'''handles the reply chat event types'''
"""Handle the reply chat event types."""
s = requests.Session()
s.headers.update({"Client-ID": self.config.CLIENTID})
event_string = {
'WelcomeEvent': 'Connected to the channel chat...',
'UserJoin': '{} has joined the channel.',
'UserLeave': '{} has left the channel.',
'ChatMessage': '{user} : {msg}',
'whisper': '{user} → {target} : {msg}',
'me': '{user} {msg}',
'PollStart': '{} has started a poll',
'PollEnd': 'The poll started by {} has ended'}

if data['event'] == 'WelcomeEvent':
print(event_string[data['event']])

elif data['event'] == 'UserJoin' or data['event'] == 'UserLeave':
if data['data']['username'] is not None:
print(event_string[data['event']].format(
data['data']['username']))

elif data['event'] == 'PollStart':
"WelcomeEvent": "Connected to the channel chat...",
"UserJoin": "{} has joined the channel.",
"UserLeave": "{} has left the channel.",
"ChatMessage": "{user}: {msg}",
"whisper": "{user} → {target} : {msg}",
"me": "{user} {msg}",
"PollStart": "{} has started a poll.",
"PollEnd": "The poll started by {} has ended.",
"ClearMessages": "{} has cleared chat.",
"PurgeMessage": "{modname} has purged {username}'s messages.",
"SkillAttribution": "{user} used the {skill} skill for {sparks}.",
"DeleteMessage": "{Mod} deleted a message."}

if data["event"] == "WelcomeEvent":
print(event_string[data["event"]])

elif data["event"] == "UserJoin" or data["event"] == "UserLeave":
if data["data"]["username"] is not None:
print(event_string[data["event"]].format(
data["data"]["username"]))

elif data["event"] == "PurgeMessage":
users_response = s.get("https://mixer.com/api/v1/users/{}".format(
data["data"]["user_id"])).json()["username"]
USERNAME = users_response
if "moderator" in data["data"]:
mod = data["data"]["moderator"]["user_name"]
print(f"{mod} has purged {USERNAME}'s messages.")
else:
pass

elif data["event"] == "DeleteMessage":
# pass
print(event_string[data["event"]].format(
Mod=data["data"]["moderator"]["user_name"]))

elif data["event"] == "ClearMessages":
print(event_string[data["event"]].format(
data["data"]["clearer"]["user_name"]))

elif data["event"] == "PollStart":
if self.poll_switch:
print(event_string[data['event']].format(
data['data']['author']['user_name']))
print(event_string[data["event"]].format(
data["data"]["author"]["user_name"]))
self.poll_switch = False

elif data['event'] == 'PollEnd':
print(event_string[data['event']].format(
data['data']['author']['user_name']))
elif data["event"] == "PollEnd":
print(event_string[data["event"]].format(
data["data"]["author"]["user_name"]))
self.poll_switch = True

elif data['event'] == 'ChatMessage':
msg = ''.join(
item["text"] for item in data['data']["message"]["message"])
if 'whisper' in data['data']['message']['meta']:
print(event_string['whisper'].format(
user=data['data']['user_name'],
target=data['data']['target'],
elif data["event"] == "SkillAttribution":
user = data["data"]["user_name"]
skill = data["data"]["skill"]["skill_name"]
sparks = data["data"]["skill"]["cost"]
print(event_string["SkillAttribution"].format(
user=user,
skill=skill,
sparks=sparks))

elif data["event"] == "ChatMessage":
msg = "".join(
item["text"] for item in data["data"]["message"]["message"])
if "whisper" in data["data"]["message"]["meta"]:
print(event_string["whisper"].format(
user=data["data"]["user_name"],
target=data["data"]["target"],
msg=msg))

elif 'me' in data['data']['message']['meta']:
print(event_string['me'].format(
user=data['data']['user_name'],
elif "me" in data["data"]["message"]["meta"]:
print(event_string["me"].format(
user=data["data"]["user_name"],
msg=msg))
else:
print(event_string[data['event']].format(
user=data['data']['user_name'],
print(event_string[data["event"]].format(
user=data["data"]["user_name"],
msg=msg))
if msg == '!ping':
self.chat.message('Its ping pong time')
if msg == "!ping":
self.chat.message("Its ping pong time")

def type_method(self, data):
'''handles the reply chat event types'''
"""Handle the reply chat event types."""
if self.config.CHATDEBUG:
if data['method'] == 'auth':
print('Authenticating with the server...')
if data["method"] == "auth":
print("Authenticating with the server...")

elif data['method'] == 'msg':
elif data["method"] == "msg":
if self.config.CHATDEBUG:
print('METHOD MSG: {}'.format(str(data)))
print(f"METHOD MSG: {str(data)}")
else:
print('METHOD MSG: {}'.format(str(data)))
print(f"METHOD MSG: {str(data)}")

def type_system(self, data):
'''handles the reply chat event types'''
"""Handle the reply chat event types."""
if self.config.CHATDEBUG:
print('SYSTEM MSG: {}'.format(str(data['data'])))
print(f"SYSTEM MSG: {str(data['data'])}")
10 changes: 5 additions & 5 deletions config.example.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
''' Config File '''
"""Config File."""

# DO NOT CHANGE THESE VALUES OR THE BOT WILL BREAK
BEAM_URI = 'https://beam.pro/api/v1/'
BEAM_URI = 'https://mixer.com/api/v1/'
USERSCURRENT_URI = 'users/current'
CHATSCID_URI = 'chats/{cid}'

# THE SETTINGS BELOW CAN BE CHANGED
# This need to be the ID for the channel you wish to join
# https://beam.pro/api/v1/channels/channelname?fields=id
# https://mixer.com/api/v1/channels/channelname?fields=id
CHANNELID = '123456'

# This is up to you to obtain. This can be done though
# Rest API. for more info https://dev.beam.pro/reference/oauth/index.html
# Rest API. for more info https://dev.mixer.com/reference/oauth/index.html
ACCESS_TOKEN = 'EnterYourAccessToken'

# Client ID, obtained from https://beam.pro/lab
# Client ID, obtained from https://mixer.com/lab
# select OAUTH CLIENTS and copy ID
CLIENTID = 'EnterYourClientID'

Expand Down
3 changes: 2 additions & 1 deletion example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""
Example chat bot that monitors incoming messages. responds to !ping command
Example chat bot that monitors incoming messages.
Responds to !ping command.
"""

from tornado.ioloop import IOLoop
Expand Down
7 changes: 4 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
'''Sets up required dependencies to run the bot'''
# -*- coding: utf-8 -*-
"""Sets up required dependencies to run the bot"""


from setuptools import setup, find_packages

setup(
name="beam-client-python",
version="0.1.0",
url="https://github.com/WatchBeam/beam-client-python",
url="https://github.com/mixer/beam-client-python",
author="Connor Peet, 2Cubed (@2CubedTech)",
author_email="[email protected]",
description="Simple chat bot framework for Beam.",
description="Simple chat bot framework for Mixer.",
license="MIT",
packages=find_packages(),
include_package_data=True,
Expand Down