Skip to content

Commit 4ed5716

Browse files
committed
Add patch v0.1.1
2 parents 3dc7e95 + 6e1a67c commit 4ed5716

File tree

4 files changed

+93
-44
lines changed

4 files changed

+93
-44
lines changed

cactus.py

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@
1111
from asyncio import get_event_loop, gather, async
1212

1313
from traceback import format_exc
14-
from time import sleep
15-
import os
1614

1715
from models import Base, engine
1816

@@ -68,19 +66,6 @@ def check_db(self):
6866
def load_config(self, filename):
6967
"""Load configuration."""
7068

71-
if os.path.exists('config.json'):
72-
self.logger.info("Config file was found. Loading...")
73-
with open(filename) as config:
74-
self.config = load(config)
75-
self.channel_data = self.login(**self.config)
76-
self.username = self.channel_data['username']
77-
else:
78-
self.logger.error("Config file was not found. Creating...")
79-
os.system('cp config-template.json config.json')
80-
self.logger.info(
81-
"Config created. Please enter information, and restart.")
82-
exit(0)
83-
8469
if exists(filename):
8570
self.logger.info("Config file was found. Loading...")
8671
with open(filename) as config:
@@ -148,5 +133,27 @@ def run(self, *args, **kwargs):
148133
self.logger.info("CactusBot deactivated.")
149134
exit()
150135

151-
cactus = Cactus(debug=True, autorestart=False)
152-
cactus.run()
136+
def _run(self, *args, **kwargs):
137+
"""Bot execution code."""
138+
139+
if self.load_config(filename=self.config_file):
140+
auth = {n: self.config[n] for n in ("username", "password")}
141+
self.bot_data = self.login(**auth)
142+
self.username = self.bot_data["username"]
143+
self.bot_id = self.bot_data["id"]
144+
self.logger.info("Authenticated as: {}.".format(self.username))
145+
146+
self.started = True
147+
148+
self.channel = self.config["channel"]
149+
self.channel_data = self.get_channel(self.channel)
150+
151+
self.logger.info("Channel {ch} (id {id}) is {status}.".format(
152+
ch=self.channel_data["token"], id=self.channel_data["id"],
153+
status=["offline", "online"][self.channel_data["online"]]
154+
))
155+
156+
157+
if __name__ == "__main__":
158+
cactus = Cactus(debug="info", autorestart=False)
159+
cactus.run()

messages.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def message_handler(self, data):
4646
"command": CommandCommand,
4747
"quote": QuoteCommand,
4848
"cube": CubeCommand,
49-
"social": SocialCommand,
49+
"social": SocialCommand
5050
}
5151
if args[0][1:] in commands:
5252
yield from self.send_message(

models.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ def add_points(self, username, amount):
210210
amount=amount
211211
)
212212
session.add(c)
213+
session.commit()
213214
else:
214215
# Todo add the user.
215216
pass
@@ -250,3 +251,12 @@ def reset_points(self, username):
250251
# TODO: Throw an error and tell the user that sent this bad things
251252
pass
252253
session.commit()
254+
255+
256+
class Schedule(Base):
257+
__tablename__ = "scheduled"
258+
259+
id = Column(Integer, unique=True, primary_key=True)
260+
text = Column(String)
261+
interval = Column(Integer)
262+
last_ran = Column(DateTime)

user.py

Lines changed: 58 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,20 @@ class User:
1010

1111
def __init__(self, debug="WARNING", **kwargs):
1212
self._init_logger(debug)
13-
print(self.authKey())
13+
self.session = Session()
1414

1515
def _init_logger(self, level):
1616
"""Initialize logger."""
1717

1818
self.logger = get_logger('CactusBot')
1919

20-
level = level.upper()
21-
2220
if level is True:
2321
level = "DEBUG"
2422
elif level is False:
2523
level = "WARNING"
2624

25+
level = level.upper()
26+
2727
levels = ("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET")
2828
if level in levels:
2929
level_num = __import__("logging").__getattribute__(level)
@@ -64,37 +64,69 @@ def request(self, req, url, **kwargs):
6464
else:
6565
self.logger.debug("Invalid request: {}".format(req))
6666

67-
def authKey(self):
68-
"""Get the required authKey from Beam"""
69-
return self.request("GET", "/chats/join")
70-
7167
def login(self, username, password, code=''):
7268
"""Authenticate and login with Beam."""
73-
return self.request("GET", "/users/login", locals())
69+
l = locals()
70+
packet = {n: l[n] for n in ("username", "password", "code")}
71+
return self.request("POST", "/users/login", data=packet)
7472

7573
def get_channel(self, id, **p):
7674
"""Get channel data by username."""
77-
channel = self.request("GET", "/channels/{id}".format(id=id))
78-
return channel
75+
return self.request("GET", "/channels/{id}".format(id=id), params=p)
76+
77+
def get_chat(self, id):
78+
"""Get chat server data."""
79+
return self.request("GET", "/chats/{id}".format(id=id))
80+
81+
def connect(self, channel_id, bot_id):
82+
"""Connect to a Beam chat through a websocket."""
83+
84+
chat = self.get_chat(channel_id)
85+
server = chat["endpoints"][0]
86+
authkey = chat["authkey"]
87+
88+
self.logger.debug("Connecting to: {server}".format(server=server))
89+
90+
self.websocket = yield from connect(server)
91+
92+
response = yield from self.send_message(
93+
(channel_id, bot_id, authkey), method="auth"
94+
)
95+
96+
response = loads(response)
97+
98+
if response["data"]["authenticated"]:
99+
self.logger.debug(response)
100+
return self.websocket
101+
return False
102+
103+
def send_message(self, arguments, method="msg"):
104+
"""Send a message to a Beam chat through a websocket."""
105+
106+
if isinstance(arguments, str):
107+
arguments = (arguments,)
79108

80-
def send_chat(self, id, message):
81-
"""
82-
Send a message for a certain chat
83-
Arguments:
84-
- id: Channel ID to send message to
85-
- message: Chat message to send
86-
"""
87-
# Packet to send to Beam
88-
# packet = {t pu}
109+
msg_packet = {
110+
"type": "method",
111+
"method": method,
112+
"arguments": arguments,
113+
"id": self.message_id
114+
}
89115

116+
yield from self.websocket.send(dumps(msg_packet))
117+
self.message_id += 1
90118

91-
class Chatter:
119+
return (yield from self.websocket.recv())
92120

93-
def ban(username):
94-
pass
121+
def remove_message(self, channel_id, message_id):
122+
"""Remove a message from chat."""
123+
return self.request("DELETE", "/chats/{id}/message/{message}".format(
124+
id=channel_id, message=message_id))
95125

96-
def purge(username):
97-
pass
126+
def read_chat(self, handle=None):
127+
while True:
128+
response = loads((yield from self.websocket.recv()))
129+
self.logger.debug(response)
98130

99-
def timeout(username, time):
100-
pass
131+
if handle:
132+
handle(response)

0 commit comments

Comments
 (0)