11# CactusBot!
22
33from messages import MessageHandler
4- from user import User
4+ from beam import Beam
55
66from os .path import exists
7- from time import sleep
8- from json import load
7+ from sys import exit
8+ from json import load , dump
99from shutil import copyfile
10+ from functools import reduce
1011
1112from asyncio import get_event_loop , gather , async
1213
1314from traceback import format_exc
15+ from time import sleep
1416
1517from models import Base , engine
1618
3840"""
3941
4042
41- class Cactus (MessageHandler , User ):
43+ class Cactus (MessageHandler , Beam ):
4244 started = False
4345 connected = False
4446 message_id = 0
@@ -48,12 +50,13 @@ def __init__(self, autorestart=True, **kwargs):
4850 self .debug = kwargs .get ("DEBUG" , False )
4951 self .autorestart = autorestart
5052 self .config_file = kwargs .get ("config_file" , "data/config.json" )
53+ self .stats_file = kwargs .get ("stats_file" , "data/stats.json" )
5154 self .database = kwargs .get ("database" , "data/data.db" )
5255
53- def check_db (self ):
56+ def _init_database (self , database ):
5457 """Ensure the database exists."""
5558
56- if exists (self . database ):
59+ if exists (database ):
5760 self .logger .info ("Found database." )
5861 else :
5962 self .logger .info ("Database wasn't found." )
@@ -67,22 +70,54 @@ def load_config(self, filename):
6770 """Load configuration."""
6871
6972 if exists (filename ):
70- self .logger .info ("Config file was found. Loading..." )
73+ self .logger .info ("Configuration file was found. Loading..." )
74+ self .config_file = filename
7175 with open (filename ) as config :
7276 self .config = load (config )
73- return True
77+ return self . config
7478 else :
75- self .logger .warn ("Config file was not found. Creating..." )
79+ self .logger .warn ("Configuration file was not found. Creating..." )
7680 copyfile ("data/config-template.json" , filename )
7781 self .logger .error (
78- "Config created. Please enter information, and restart." )
79- raise FileNotFoundError ("Config not found." )
82+ "Configuration file created. Please enter values and restart." )
83+ raise FileNotFoundError ("Configuration not found." )
84+ exit ()
85+
86+ def load_stats (self , filename ):
87+ if exists (filename ):
88+ self .stats_file = filename
89+ self .logger .info ("Statistics file was found. Loading..." )
90+ with open (filename ) as stats :
91+ self .stats = load (stats )
92+ return self .stats
93+ else :
94+ self .logger .warn ("Statistics file was not found. Creating..." )
95+ copyfile ("data/stats-template.json" , "data/stats.json" )
96+ self .logger .info ("Statistics file created." )
97+
98+ def update_config (self , keys , value ):
99+ with open (self .config_file , 'r' ) as config :
100+ config_data = load (config )
101+ reduce (lambda d , k : d [k ], keys .split ('.' )[:- 1 ], config_data )[
102+ keys .split ('.' )[- 1 ]] = value
103+ with open (self .config_file , 'w+' ) as config :
104+ dump (config_data , config , indent = 4 , sort_keys = True )
105+ self .config = config_data
106+
107+ def update_stats (self , keys , value ):
108+ with open (self .stats_file , 'r' ) as stats :
109+ stats_data = load (stats )
110+ reduce (lambda d , k : d [k ], keys .split ('.' )[:- 1 ], stats_data )[
111+ keys .split ('.' )[- 1 ]] = value
112+ with open (self .config_file , 'w+' ) as config :
113+ dump (stats_data , config , indent = 4 , sort_keys = True )
114+ self .config = stats_data
80115
81116 def run (self , * args , ** kwargs ):
82117 """Run bot."""
83118
84119 self .logger .info (cactus_art )
85- self .check_db ( )
120+ self ._init_database ( self . database )
86121
87122 while self .autorestart or not self .started :
88123 try :
@@ -91,11 +126,11 @@ def run(self, *args, **kwargs):
91126 loop = get_event_loop ()
92127
93128 self .connected = bool (loop .run_until_complete (
94- self .connect (self .channel_data ['id' ], self .bot_data ['id' ])
129+ self .connect (self .channel_data ["id" ], self .bot_data ["id" ])
95130 ))
96131
97132 self .logger .info ("{}uccessfully connected to chat {}." .format (
98- [' Uns' , 'S' ][self .connected ], self .channel_data ["token" ]
133+ [" Uns" , "S" ][self .connected ], self .channel_data ["token" ]
99134 ))
100135
101136 if self .connected :
@@ -137,8 +172,8 @@ def _run(self, *args, **kwargs):
137172 """Bot execution code."""
138173
139174 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 )
175+ self .load_stats ( filename = self . stats_file )
176+ self .bot_data = self .login (** self . config [ " auth" ] )
142177 self .username = self .bot_data ["username" ]
143178 self .bot_id = self .bot_data ["id" ]
144179 self .logger .info ("Authenticated as: {}." .format (self .username ))
@@ -153,7 +188,9 @@ def _run(self, *args, **kwargs):
153188 status = ["offline" , "online" ][self .channel_data ["online" ]]
154189 ))
155190
191+ self ._init_commands ()
192+
156193
157194if __name__ == "__main__" :
158- cactus = Cactus (debug = "info " , autorestart = False )
195+ cactus = Cactus (debug = "debug " , autorestart = False , log_to_file = True )
159196 cactus .run ()
0 commit comments