-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·419 lines (349 loc) · 17 KB
/
main.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# LamiaDMBot's main class based upon echobot2.py
"""
LamiaDMBot's main class based upon echobot2.py
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging, sqlite3, ConfigParser, os, re, sys
from roll import *
from storage import *
from char import *
from collections import OrderedDict
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Token declaration
TOKEN = "TOKEN"
# Default database path
DBPATH = "lamia.db"
# Version information
VERSION = "v0.5.6"
# Define a few helper functions
def readconfig(config_filename='lamia.cfg'):
global TOKEN, DBPATH
config = ConfigParser.ConfigParser()
if not os.path.isfile(config_filename): #if the config file doesn't exist already, we'll create one
logger.info("Creating a new config file and exiting immediately. Make sure to replace the default token value with your own!")
config_file = open(config_filename, 'w')
config.add_section('main')
config.set('main', 'token', 'TOKEN')
config.set('main', 'dbpath', DBPATH)
config.set('main', 'ratelimit', '1000')
config.write(config_file)
config_file.close()
sys.exit()
else:
config.read(config_filename)
# logger.info("Read token: %s", config.get('main', 'token'))
TOKEN = config.get('main', 'token')
DBPATH = config.get('main', 'dbpath')
return config
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update, args):
db = LamiaDB(DBPATH)
bot.sendMessage(update.message.chat_id, text='Hiya! Type /help to get a list of all my actions.')
if db.register_user(update.message.from_user.id):
bot.sendMessage(update.message.chat_id, text='New user registered. Now you can store rolls and characters!')
db.conn.close()
def help(bot, update):
bot.sendMessage(update.message.chat_id, text="""/start Secret - Allows you to register with the bot. A password may have been specified by the bot's maintainer.
/roll xdy - Rolls X Y-sided dice.
Other optional arguments, in order of precedence:
- Add "&" followed by a number to repeat the roll that many times.
- Add "!" to use exploding dice.
- Use "+" or "-" to add a modifier that adds or substracts that amount to the sum.
- Use ">" or "<" to count successes when rolling over or rolling under the specified amount. In this mode, the modifier adds or substracts successes.
- Use "D" or "K" to Drop a certain amount of lowest dice or Keep a certain amount of highest dice.
The bot supports FATE-style dice. In order to use them, use the xdF notation. For example, /roll 4dF tells the bot to roll four FATE dice.
/aroll Roll/RollName - Roll with advantage (The higher of two rolls is selected).
/droll Roll/RollName - Roll with disadvantage (The lower of two rolls is selected).
/sroll RollName Roll - Lets you store rolls for future use. Give the roll an identifier and then call it by name. Requires user registration.
/sroll RollName - Lets you recall a stored roll.
/listroll - Provides a list of all the stored rolls you have.
/delroll Roll - Lets you delete a stored roll.
/newchar CharacterName Attributename Attributevalue - Lets you register a new character. Requires user registration.
/char CharacterName - Displays the name and attributes of a given character.
/listchar - Provides a list of all the characters you have.
/delchar CharacterName - Lets you delete a stored character.
/attr CharacterName Attributename Attributevalue - Adds or changes the given character's attribute.
/delattr CharacterName Attributename - Deletes the given character's attribute.
/about - Shows the bot's current running version and copyright info.""")
# Define some testing functions
def fullnewchar(bot, update, args):
# First argument: character identifier
# Second argument: character name (between double quotes)
# Third argument: campaign name (between double quotes)
# Fourth argument: campaign system (between double quotes)
args_str = ' '.join(args)
pattern = r'\"(.+?)\"'
matches = re.findall(pattern, args_str)
pass
def newdesc(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
args_str = ' '.join(args)
pattern_quotetext = r'\"(.+?)\"'
pattern_url = r'^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$'
pass
def desc(bot, update, args):
pass
def deldesc(bot, update, args):
pass
#The rest
def echo(bot, update):
bot.sendMessage(update.message.chat_id, text=update.message.text)
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def rolldie(bot, update, args):
roll = Roll(args[0])
#bot.sendMessage(update.message.chat_id, text=' '.join(args))
if len(roll.result) > 0:
msg = u""
for x in range(0, roll.repeat):
msg += ("# " + str(x+1) + "\n") if roll.repeat > 1 else ""
if roll.rollunder == 0 and roll.rollover == 0:
msg += roll.rollparams + " | " + ' '.join(map(str, roll.result)) + \
" (" + ("+" if (roll.modifier > 0) else "") + \
str(roll.modifier) + ") = " + str(roll.sum)
else:
msg += roll.rollparams + " | " + ' '.join(map(str, roll.result)) + \
" (" + ("+" if (roll.modifier > 0) else "") + \
str(roll.modifier) + ") \n" + str(roll.sum) + " successes, " + str(roll.fail) + " failures."
roll = Roll(args[0])
if roll.optwarnings:
msg = (roll.optwarnings + "\n") + msg
msg += "\n"
if len(msg) < 4096: #The maximum message size in Telegram
bot.sendMessage(update.message.chat_id, text=msg, reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid roll.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid roll.", reply_to_message_id=update.message.message_id)
def aroll(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
#First, we'll test if it's a valid roll outright
if Roll.is_valid_roll(args[0]):
roll1 = Roll(args[0])
roll2 = Roll(args[0])
else: #We'll now test if it could be a recalled roll. TODO: Fix edge case in which a valid stored roll's name can be in itself a valid roll, don't wanna do this shit right now
sroll = db.fetch_roll(userid, args[0])[0]
roll1 = Roll(sroll)
roll2 = Roll(sroll)
#Now, which one is the highest?
if roll1.sum >= roll2.sum:
roll1_sum = "[" + str(roll1.sum) + "]"
roll2_sum = str(roll2.sum)
else:
roll2_sum = "[" + str(roll2.sum)+ "]"
roll1_sum = str(roll1.sum)
if len(roll1.result) > 0:
bot.sendMessage(update.message.chat_id, text="Rolling with advantage: " + roll1.rollparams + "\n" + \
roll1_sum + " | " + roll2_sum, reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid roll.", reply_to_message_id=update.message.message_id)
db.conn.close()
def droll(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
#First, we'll test if it's a valid roll outright
if Roll.is_valid_roll(args[0]):
roll1 = Roll(args[0])
roll2 = Roll(args[0])
else: #We'll now test if it could be a recalled roll. TODO: Fix edge case in which a valid stored roll's name can be in itself a valid roll, don't wanna do this shit right now
sroll = db.fetch_roll(userid, args[0])[0]
roll1 = Roll(sroll)
roll2 = Roll(sroll)
#Now, which one is the lowest?
if roll1.sum < roll2.sum:
roll1_sum = "[" + str(roll1.sum) + "]"
roll2_sum = str(roll2.sum)
else:
roll2_sum = "[" + str(roll2.sum)+ "]"
roll1_sum = str(roll1.sum)
if len(roll1.result) > 0:
bot.sendMessage(update.message.chat_id, text="Rolling with disadvantage: " + roll1.rollparams + "\n" + \
roll1_sum + " | " + roll2_sum, reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid roll.", reply_to_message_id=update.message.message_id)
db.conn.close()
def storedroll(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
#check in which case we're in: is there a single argument?
if len(args) == 1: #single argument
#Then we're looking for a previously stored roll
sroll_name = args[0]
retrieved_roll = db.fetch_roll(userid, sroll_name)
if not (retrieved_roll == None):
rolldie(bot, update, retrieved_roll)
else:
bot.sendMessage(update.message.chat_id, text="Error: Stored roll not found.", reply_to_message_id=update.message.message_id)
elif len(args) == 2: #two arguments
#then we're storing a new roll
sroll_name = args[0]
sroll_value = args[1]
if not db.is_roll_registered(userid, sroll_name):
if Roll.is_valid_roll(sroll_value):
if db.register_roll(userid, sroll_name, sroll_value):
bot.sendMessage(update.message.chat_id, text="New roll stored.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error trying to register roll. Are you registered yet?", \
reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid roll.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: There is a stored roll with the same name.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
#bot.sendMessage(update.message.chat_id, text=' '.join(args))
db.conn.close()
def listroll(bot, update):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
roll_list = db.fetch_all_rolls(userid).keys()
bot.sendMessage(update.message.chat_id, text="Your stored rolls: " + ' '.join(map(str, roll_list)), reply_to_message_id=update.message.message_id)
db.conn.close()
def delroll(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) == 1: #command takes a single argument
sroll_name = args[0]
if db.delete_roll(userid, sroll_name):
bot.sendMessage(update.message.chat_id, text="Roll deleted.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Roll not found.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def char(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) == 1: #command takes a single argument
charname = args[0]
chardict = db.fetch_character(userid, charname)
chardict = OrderedDict(sorted(chardict.items(), key=lambda t: t[0])) #Order dictionary by key
if chardict == {}:
bot.sendMessage(update.message.chat_id, text="Error: Character not found.", reply_to_message_id=update.message.message_id)
else:
output = ""
for key, value in chardict.iteritems():
output += (key + ": " + value + "\n")
bot.sendMessage(update.message.chat_id, text=output, reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def newchar(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) >= 1: #command takes at least one argument
charname = args[0]
attriter = iter(args[1:])
attrdict = dict(zip(attriter, attriter))
reg = db.register_character(userid, charname)
if reg and attrdict != {}: #Character registation was a success and there's at least one attribute value
for key, value in attrdict.iteritems():
db.add_attribute(userid, charname, key, value)
bot.sendMessage(update.message.chat_id, text="Character registered successfully.", reply_to_message_id=update.message.message_id)
elif reg:
bot.sendMessage(update.message.chat_id, text="Character registered successfully.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error while attempting to register a new character.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def listchar(bot, update):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
character_list = db.fetch_all_characters(userid)
bot.sendMessage(update.message.chat_id, text="Your characters: " + ' '.join(map(str, character_list)), reply_to_message_id=update.message.message_id)
def charattr(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) >= 3: #command takes at least three arguments
charname = args[0]
attriter = iter(args[1:])
attrdict = dict(zip(attriter, attriter))
for key, value in attrdict.iteritems():
if not db.add_attribute(userid, charname, key, value):
if not db.change_attribute(userid, charname, key, value):
bot.sendMessage(update.message.chat_id, text="Error while attempting to record or change an attribute.", \
reply_to_message_id=update.message.message_id)
bot.sendMessage(update.message.chat_id, text="Attributes changed.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def delchar(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) == 1: #command takes a single argument
if not db.delete_character(userid, args[0]):
bot.sendMessage(update.message.chat_id, text="Error while attempting to delete a character.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Character deleted.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def delcharattr(bot, update, args):
db = LamiaDB(DBPATH)
userid = update.message.from_user.id
if len(args) == 2: #command takes three arguments
if db.remove_attribute(userid, args[0], args[1]):
bot.sendMessage(update.message.chat_id, text="Attribute removed.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error removing a character attribute.", reply_to_message_id=update.message.message_id)
else:
bot.sendMessage(update.message.chat_id, text="Error: Invalid number of arguments.", reply_to_message_id=update.message.message_id)
db.conn.close()
def aboutbot(bot, update):
bot.sendMessage(update.message.chat_id, text="LamiaDMBot " + VERSION + "\nBy EntropiaFox\nReleased under the terms of the GPL v3 License", \
reply_to_message_id=update.message.message_id)
def main():
try:
# Read the configuration for the bot
if(len(sys.argv) >= 2 and sys.argv[1]):
logger.info("Loading up config: %s", sys.argv[1])
config = readconfig(sys.argv[1]) # Takes config path optionally as an argument
else:
config = readconfig()
# Create the EventHandler and pass it your bot's token.
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start, pass_args=True))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("roll", rolldie, pass_args=True))
dp.add_handler(CommandHandler("aroll", aroll, pass_args=True))
dp.add_handler(CommandHandler("droll", droll, pass_args=True))
dp.add_handler(CommandHandler("sroll", storedroll, pass_args=True))
dp.add_handler(CommandHandler("listroll", listroll))
dp.add_handler(CommandHandler("delroll", delroll, pass_args=True))
dp.add_handler(CommandHandler("char", char, pass_args=True))
dp.add_handler(CommandHandler("newchar", newchar, pass_args=True))
dp.add_handler(CommandHandler("listchar", listchar))
dp.add_handler(CommandHandler("delchar", delchar, pass_args=True))
dp.add_handler(CommandHandler("attr", charattr, pass_args=True))
dp.add_handler(CommandHandler("delattr", delcharattr, pass_args=True))
dp.add_handler(CommandHandler("about", aboutbot))
# on noncommand i.e message - echo the message on Telegram
#dp.add_handler(MessageHandler([Filters.text], echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
except:
#Exception handling
logger.exception("Exception raised.")
if __name__ == '__main__':
main()