forked from JohnRipper/quantum
/
bot.py
191 lines (164 loc) · 6.85 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
import getopt
import websockets
import concurrent.futures
import asyncio
import requests
import json
import re as regex
import sys
import time
import logging
import importlib
from pathlib import Path
import tomlkit
from lib import constants
from lib.command import Command
logging.basicConfig(
level=logging.INFO,
format="%(threadName)10s : %(message)s",
)
class QuantumBot:
def __init__(self):
self.ws = None
self.accounts = {}
self.log = logging.getLogger("tc_bot")
self.settings = None
self.rate_limit_seconds = 1
self.message_queue = []
self.is_running = False
self.cogs = []
self.handle = 0
async def attempt_command(self, cmd:Command):
for cog in self.cogs:
#todo make it work for aliases
if hasattr(cog, cmd.command):
f = getattr(cog, cmd.command)
# commands only run if they were given the _command meta data from the @command decorator
if hasattr(f, "_command"):
if f._command:
await getattr(cog, cmd.command)(cmd)
def load_config(self, config=None):
default_config = Path("default.toml")
possible_config = Path(config) if config != None else None
if config is None and default_config.exists():
print("Using default config")
_config = default_config
elif possible_config and possible_config.exists():
# toml suffix isn't really needed, might be worth checking later
# if possible_config.suffix == ".toml":
_config = possible_config
else:
sys.exit("config could not be found")
self.settings = tomlkit.loads(_config.read_text())
self.load_cogs()
def load_cogs(self):
for cog_name in self.settings["bot"]["modules"]:
print(f"Loaded {cog_name}")
self.add_cog(cog_name)
async def connect(self):
self.log.info("starting")
r = requests.session()
data = r.get(url="https://tinychat.com/start?#signin")
csrf = regex.search(string=data.text,
pattern=r"<meta name=\"csrf-token\" id=\"csrf-token\" content=\"[a-zA-Z0-9]*").group(0)[49:]
s_data = {
"login_username": self.settings["account"]["username"],
"login_password": self.settings["account"]["password"],
"remember": "1",
"_token": csrf
}
r.post(url="https://tinychat.com/login", data=s_data)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
}
token = r.get(url="https://tinychat.com/api/v1.0/room/token/" + self.settings["room"]["roomname"])
rtc_version_data = r.get(url="https://tinychat.com/room/" + self.settings["room"]["roomname"])
rtc_version = regex.search(string=rtc_version_data.text, pattern=r"href=\"/webrtc/[0-9-.]*").group(0)[13:]
payload = {
"tc": "join",
"req": 1,
"useragent": "tinychat-client-webrtc-chrome_linux x86_64-" + rtc_version,
"token": token.json()["result"],
"room": self.settings["room"]["roomname"],
"nick": self.settings["room"]["nickname"]
}
r.close()
async with websockets.connect(uri=token.json()["endpoint"], subprotocols=["tc"],
extra_headers=headers, timeout=600, origin="https://tinychat.com") as self.ws:
await self.ws.send(json.dumps(payload))
self.is_running = True
async for message in self.ws:
await self.consumer(message)
def add_cog(self, cog_name: str):
m = importlib.import_module(f"modules.{cog_name.lower()}")
cog_class = getattr(m, cog_name)
cog = cog_class(bot=self)
self.cogs.append(cog)
def remove_cog(self, cog_name: str):
for cog in self.cogs:
if cog.name == cog_name:
self.cogs.remove(cog)
async def password(self):
await self.ws.send(json.dumps({"tc":"password","req":2,"password":self.settings["room"]["password"]}))
async def consumer(self, message: str):
print(message)
tiny_crap = json.loads(message)
if tiny_crap["tc"] == "userlist":
for user in tiny_crap["users"]:
self.accounts.update({user["handle"]: user["nick"]})
if tiny_crap["tc"] == "joined":
self.handle = tiny_crap["self"]["handle"]
if tiny_crap["tc"] == "join":
self.accounts.update({tiny_crap["handle"]: tiny_crap["nick"]})
if tiny_crap["tc"] == "quit":
self.accounts.pop(tiny_crap["handle"])
if tiny_crap["tc"] == "ping":
await self.pong()
if tiny_crap["tc"] == "msg":
# check for a command, decorators are optional you can do it manually overriding msg in cog
for prefix in self.settings["bot"]["prefixes"]:
# if prefix match continue
if tiny_crap["text"].startswith(prefix):
await self.attempt_command(Command(data=tiny_crap))
if tiny_crap["tc"] == "password":
await self.password()
# runs cog events
for type in constants.T_OBJECTS:
if tiny_crap["tc"] == type:
for cog in self.cogs:
await getattr(cog, type.lower())(tiny_crap)
def handle_to_name(self, handle):
return self.accounts[handle]
async def send_message(self, message):
if len(self.message_queue) > 0:
self.message_queue.append(message)
else:
await self.ws.send(json.dumps({"tc": "msg", "req":1, "text":message}))
async def pong(self):
await self.ws.send(json.dumps({"tc": "pong", "req": 1}))
def process_message_queue(self):
while self.is_running:
if len(self.message_queue) > 0:
self.send_message(message= self.message_queue.pop(0))
time.sleep(self.rate_limit_seconds)
def process_arg(arg, b: QuantumBot):
try:
opts, args = getopt.getopt(arg, "c:", ["config="])
except getopt.GetoptError:
print("Bot.py -c <configfile>")
sys.exit(2)
# load default config if one is not specified.
if not opts:
b.load_config()
for opt, arg in opts:
if opt == "-c":
b.load_config(arg)
async def start(executor, bot):
asyncio.get_event_loop().run_in_executor(executor, bot.process_message_queue),
await bot.connect()
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3,)
bot = QuantumBot()
process_arg(sys.argv[1:], bot)
asyncio.get_event_loop().run_until_complete(start(executor, bot))