-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathbot.py
More file actions
246 lines (195 loc) · 8.02 KB
/
bot.py
File metadata and controls
246 lines (195 loc) · 8.02 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
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
"""
botogram.bot
The actual bot application base
Copyright (c) 2015 Pietro Albini <pietro@pietroalbini.io>
Released under the MIT license
"""
import re
import logbook
import uuid
import requests.exceptions
from . import api
from . import objects
from . import runner
from . import defaults
from . import components
from . import utils
from . import frozenbot
from . import shared
from . import tasks
class Bot(frozenbot.FrozenBot):
"""A botogram-made bot"""
def __init__(self, api_connection):
self.logger = logbook.Logger('botogram bot')
self.api = api_connection
self.about = ""
self.owner = ""
self.hide_commands = ["start"]
self.before_help = []
self.after_help = []
self.process_backlog = False
self._lang = ""
self._lang_inst = None
# Set the default language to english
self.lang = "en"
self._components = []
self._main_component = components.Component("")
self._main_component_id = self._main_component._component_id
# Setup shared state
self.shared = shared.SharedStateManager()
# Register bot's shared memory initializers
inits = self._main_component._get_chains()["memory_preparers"][0]
maincompid = self._main_component._component_id
# TODO: FIXME
#self._shared_memory.register_preparers_list(maincompid, inits)
# Setup the scheduler
self._scheduler = tasks.Scheduler()
self._bot_id = str(uuid.uuid4())
self.use(defaults.DefaultComponent())
self.use(self._main_component, only_init=True)
# Fetch the bot itself's object
try:
self.itself = self.api.call("getMe", expect=objects.User)
except api.APIError as e:
self.logger.error("Can't connect to Telegram!")
if e.error_code == 401:
self.logger.error("The API token seems to be invalid.")
else:
self.logger.error("Response from Telegram: %s" % e.description)
exit(1)
except requests.exceptions.ConnectionError:
self.logger.error("Can't reach Telegram servers! Are you sure "
"you're connected to the internet?")
exit(1)
# This regex will match all commands pointed to this bot
self._commands_re = re.compile(r'^\/([a-zA-Z0-9_]+)(@' +
self.itself.username + r')?( .*)?$')
def __reduce__(self):
# Use the standard __reduce__
return object.__reduce__(self)
def __setattr__(self, name, value):
# Use the standard __setattr__
return object.__setattr__(self, name, value)
def before_processing(self, func):
"""Register a before processing hook"""
self._main_component.add_before_processing_hook(func)
return func
def process_message(self, func):
"""Add a message processor hook"""
self._main_component.add_process_message_hook(func)
return func
def message_equals(self, string, ignore_case=True):
"""Add a message equals hook"""
def __(func):
self._main_component.add_message_equals_hook(string, func,
ignore_case)
return func
return __
def message_contains(self, string, ignore_case=True, multiple=False):
"""Add a message contains hook"""
def __(func):
self._main_component.add_message_contains_hook(string, func,
ignore_case,
multiple)
return func
return __
def message_matches(self, regex, flags=0, multiple=False):
"""Add a message matches hook"""
def __(func):
self._main_component.add_message_matches_hook(regex, func, flags,
multiple)
return func
return __
def command(self, name):
"""Register a new command"""
def __(func):
self._main_component.add_command(name, func, _from_main=True)
return func
return __
def timer(self, interval):
"""Register a new timer"""
def __(func):
self._main_component.add_timer(interval, func)
return func
return __
def prepare_memory(self, func):
"""Register a shared memory's preparer"""
self._main_component.add_memory_preparer(func)
return func
@utils.deprecated("@bot.init_shared_memory", "1.0", "Rename the decorator "
"to @bot.prepare_memory")
def init_shared_memory(self, func):
"""This decorator is deprecated, and it calls @prepare_memory"""
return self.prepare_memory(func)
def chat_unavailable(self, func):
"""Add a chat unavailable hook"""
self._main_component.add_chat_unavailable_hook(func)
return func
def use(self, *components, only_init=False):
"""Use the provided components in the bot"""
for component in components:
if not only_init:
self.logger.debug("Component %s just loaded into the bot" %
component.component_name)
self._components.append(component)
# Register initializers for the shared memory
chains = component._get_chains()
compid = component._component_id
preparers = chains["memory_preparers"][0]
# TODO: FIXME
#self._shared_memory.register_preparers_list(compid, preparers)
# Register tasks
self._scheduler.register_tasks_list(chains["tasks"][0])
def process(self, update):
"""Process an update object"""
# Updates are always processed in a frozen instance
# This way there aren't inconsistencies between the runner and manual
# update processing
frozen = self.freeze()
return frozen.process(update)
def run(self, workers=2):
"""Run the bot with the multi-process runner"""
inst = runner.BotogramRunner(self, workers=workers)
inst.run()
def freeze(self):
"""Return a frozen instance of the bot"""
chains = components.merge_chains(self._main_component,
*self._components)
# Get the list of commands for the bot
commands = self._components[-1]._get_commands()
for component in reversed(self._components[:-1]):
commands.update(component._get_commands())
commands.update(self._main_component._get_commands())
return frozenbot.FrozenBot(self.api, self.about, self.owner,
self.hide_commands, self.before_help,
self.after_help, self.process_backlog,
self.lang, self.itself, self._commands_re,
commands, chains, self._scheduler,
self._main_component._component_id,
self._bot_id, self.shared)
@property
def lang(self):
return self._lang
@lang.setter
def lang(self, lang):
"""Update the bot's language"""
if lang == self._lang:
return
self._lang_inst = utils.get_language(lang)
self._lang = lang
def _get_commands(self):
"""Get all the commands this bot implements"""
result = {}
for component in self._components:
result.update(component._get_commands())
result.update(self._main_component._get_commands())
return result
def create(api_key, *args, **kwargs):
"""Create a new bot"""
conn = api.TelegramAPI(api_key)
return Bot(conn, *args, **kwargs)
def channel(name, api_key):
"""Get a representation of a channel"""
conn = api.TelegramAPI(api_key)
obj = objects.Chat({"id": 0, "type": "channel", "username": name}, conn)
return obj