This repository has been archived by the owner on May 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
component_discord_bot.py
150 lines (107 loc) · 5.18 KB
/
component_discord_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
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.types import RegisterOptions, PublishOptions
from autobahn.wamp import auth
from config import config
import aioredis
import discord
import json
import requests
class DiscordBotComponent:
@classmethod
def run(cls):
print(f"Starting {cls.__name__}...")
url = f"ws://{config['crossbar']['host']}:{config['crossbar']['port']}"
runner = ApplicationRunner(url=url, realm=config["crossbar"]["realm"])
runner.run(DiscordBotWAMPComponent)
class DiscordBotWAMPComponent(ApplicationSession):
def __init__(self, c=None):
super().__init__(c)
def onConnect(self):
self.join(config["crossbar"]["realm"], ["wampcra"], config["crossbar"]["auth"]["username"])
def onDisconnect(self):
print("Disconnected from Crossbar!")
def onChallenge(self, challenge):
secret = config["crossbar"]["auth"]["password"]
signature = auth.compute_wcs(secret.encode('utf8'), challenge.extra['challenge'].encode('utf8'))
return signature.decode('ascii')
async def onJoin(self, details):
self.redis_client = await self._initialize_redis_client()
self.messages = dict()
self.discord = discord.Client()
@self.discord.event
async def on_ready():
bot_channel = None
for server in self.discord.guilds:
if server.name == config["discord"]["server"]:
for channel in server.channels:
if channel.name == config["discord"]["channel"]:
bot_channel = channel
async def on_online(payload):
try:
if payload['type'] != "live":
return None
if self.messages.get(payload["channel_id"]) is not None:
return None
channel = await self.fetch_channel(payload['channel_id'])
game = await self.fetch_game(payload['game_id'])
escaped_display_name = channel['display_name'].replace('_', '\\_')
twitch_url = f"https://www.twitch.tv/{channel['login']}"
message = f"@everyone {escaped_display_name} has gone live! {twitch_url}"
embed = discord.Embed(title=twitch_url, colour=discord.Colour(0x4b367c))
embed.set_thumbnail(url=channel['profile_image_url'])
embed.set_author(name=f"{channel['display_name']} is now streaming!", url=twitch_url)
embed.set_footer(text=config["discord"]["server"])
embed.add_field(name="Category", value=game['name'], inline=False)
embed.add_field(name="Title", value=payload["title"], inline=False)
discord_message = await bot_channel.send(message, embed=embed)
self.messages[payload["channel_id"]] = discord_message
except Exception:
pass
async def on_offline(payload):
try:
message = self.messages.get(payload['channel_id'])
if message:
await message.delete()
del self.messages[payload['channel_id']]
except Exception:
pass
await self.subscribe(on_online, "CHANNEL:ONLINE")
await self.subscribe(on_offline, "CHANNEL:OFFLINE")
await self.discord.login(config["credentials"]["discord"]["bot_user_token"])
await self.discord.connect()
async def fetch_channel(self, channel_id):
redis_key = f"{config['redis']['prefix']}:CHANNEL:{channel_id}"
channel_data = await self.redis_client.get(redis_key)
if channel_data is None:
url = f"https://api.twitch.tv/helix/users?id={channel_id}"
response = requests.get(
url,
headers={"Client-ID": config["credentials"]["twitch"]["client_id"]}
)
channel_data = response.json()["data"][0]
await self.redis_client.setex(redis_key, 1209600, json.dumps(channel_data))
else:
channel_data = json.loads(channel_data.decode("utf-8"))
return channel_data
async def fetch_game(self, game_id):
redis_key = f"{config['redis']['prefix']}:GAME:{game_id}"
game_data = await self.redis_client.get(redis_key)
if game_data is None:
url = f"https://api.twitch.tv/helix/games?id={game_id}"
response = requests.get(
url,
headers={"Client-ID": config["credentials"]["twitch"]["client_id"]}
)
game_data = response.json()["data"][0]
await self.redis_client.set(redis_key, json.dumps(game_data))
else:
game_data = json.loads(game_data.decode("utf-8"))
return game_data
async def _initialize_redis_client(self):
return await aioredis.create_redis(
(config["redis"]["host"], config["redis"]["port"]),
loop=asyncio.get_event_loop()
)
if __name__ == "__main__":
DiscordBotComponent.run()