forked from shawnanastasio/python-matrix-bot-api
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_bot.py
More file actions
Latest commit
84 lines (60 loc) · 2.2 KB
/
Copy pathexample_bot.py
File metadata and controls
84 lines (60 loc) · 2.2 KB
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
"""
importrandom
frommatrix_bot_api.matrix_bot_apiimportMatrixBotAPI
frommatrix_bot_api.mregex_handlerimportMRegexHandler
frommatrix_bot_api.mcommand_handlerimportMCommandHandler
# Global variables
USERNAME=""# Bot's username
PASSWORD=""# Bot's password
SERVER=""# Matrix server URL
defhi_callback(room, event):
# Somebody said hi, let's say Hi back
room.send_text("Hi, "+event['sender'])
defecho_callback(room, event):
args=event['content']['body'].split()
args.pop(0)
# Echo what they said back
room.send_text(' '.join(args))
defdieroll_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
ifnotdie_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)
ifdie_max<=1ordie_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))
defmain():
# 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
whileTrue:
input()
if__name__=="__main__":
main()