-
Notifications
You must be signed in to change notification settings - Fork 34
/
example_bot.py
84 lines (60 loc) · 2.2 KB
/
example_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
"""
A test bot using the Python Matrix Bot API
Test it out by adding it to a group chat and doing one of the following:
1. Say "Hi"
2. Say !echo this is a test!
3. Say !d6 to get a random size-sided die roll result
"""
import random
from matrix_bot_api.matrix_bot_api import MatrixBotAPI
from matrix_bot_api.mregex_handler import MRegexHandler
from matrix_bot_api.mcommand_handler import MCommandHandler
# Global variables
USERNAME = "" # Bot's username
PASSWORD = "" # Bot's password
SERVER = "" # Matrix server URL
def hi_callback(room, event):
# Somebody said hi, let's say Hi back
room.send_text("Hi, " + event['sender'])
def echo_callback(room, event):
args = event['content']['body'].split()
args.pop(0)
# Echo what they said back
room.send_text(' '.join(args))
def dieroll_callback(room, event):
# someone wants a random number
args = event['content']['body'].split()
# we only care about the first arg, which has the die
die = args[0]
die_max = die[2:]
# ensure the die is a positive integer
if not die_max.isdigit():
room.send_text('{} is not a positive number!'.format(die_max))
return
# and ensure it's a reasonable size, to prevent bot abuse
die_max = int(die_max)
if die_max <= 1 or die_max >= 1000:
room.send_text('dice must be between 1 and 1000!')
return
# finally, send the result back
result = random.randrange(1,die_max+1)
room.send_text(str(result))
def main():
# Create an instance of the MatrixBotAPI
bot = MatrixBotAPI(USERNAME, PASSWORD, SERVER)
# Add a regex handler waiting for the word Hi
hi_handler = MRegexHandler("Hi", hi_callback)
bot.add_handler(hi_handler)
# Add a regex handler waiting for the echo command
echo_handler = MCommandHandler("echo", echo_callback)
bot.add_handler(echo_handler)
# Add a regex handler waiting for the die roll command
dieroll_handler = MCommandHandler("d", dieroll_callback)
bot.add_handler(dieroll_handler)
# Start polling
bot.start_polling()
# Infinitely read stdin to stall main thread while the bot runs in other threads
while True:
input()
if __name__ == "__main__":
main()