forked from tian2992/tio_chema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
executable file
·192 lines (155 loc) · 6.12 KB
/
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
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
#!/usr/bin/env python2
import time, sys, re
import logging
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol, threads, defer
from twisted.python import log
from yapsy.PluginManager import PluginManager
from configobj import ConfigObj
from ircmessage import IRCMessage
from plugins.baseactionplugin import BaseActionPlugin
from plugins.texttriggerplugin import TextTriggerPlugin
class ChemaBot(irc.IRCClient):
"""The main IRC bot class.
ChemaBot mainly handles message dispatching
to plugins and other general bot functions.
"""
def __init__(self, nickname):
self.nickname = nickname
logging.basicConfig(level=logging.DEBUG)
self.plugins_init()
def plugins_init(self, is_reloading = False):
if is_reloading:
logging.info("Deactivating All Plugins")
for pluginInfo in self.pm.getAllPlugins():
self.pm.deactivatePluginByName(pluginInfo.name)
self.pm = PluginManager(
categories_filter = {
"BaseActions" : BaseActionPlugin,
"TextActions" : TextTriggerPlugin,
},
directories_list=["plugins"],)
self.pm.collectPlugins()
for pluginInfo in self.pm.getAllPlugins():
self.pm.activatePluginByName(pluginInfo.name)
logging.info("Plugin {0} activated".format(pluginInfo.name))
# TODO: create a list of localized ("_()") plugin triggers
# Create a dictionary of the names of all the plugins
self.action_plugins = {}
# List of the regexes and plugins
self.text_trigger_plugins = []
# TODO: specify categories of plugins with each trigger http://yapsy.sourceforge.net/PluginManager.html
for pluginInfo in self.pm.getPluginsOfCategory("BaseActions"):
self.action_plugins[pluginInfo.name] = pluginInfo.plugin_object
for pluginInfo in self.pm.getPluginsOfCategory("TextActions"):
self.text_trigger_plugins.append((pluginInfo.plugin_object.trigger, pluginInfo.plugin_object))
# Useful for debugging
def listPlugins(self):
print 'Plugins:'
for item in self.plugins:
print item
def signedOn(self):
"""Called when bot has succesfully signed on to server."""
self.join(self.factory.channel)
def joined(self, channel):
"""This will get called when the bot joins the channel."""
pass
def emitMessage(self, message, channel = None):
"""A function to abstract message emission."""
if channel:
self.msg(channel, message.render().encode('utf-8'))
## Handling private messages.
elif message.channel == self.nickname:
self.msg(message.user.split("!")[0], message.render().encode('utf-8'))
else:
self.msg(message.channel, message.render().encode('utf-8'))
def _parseAndExecute(self, ircm):
"""Recieves an IRCMessage, detects the command and triggers the appropiate plugin."""
message = ircm.msg
for (text_trigger, plugin) in self.text_trigger_plugins:
if isinstance(text_trigger, type(re.compile(''))):
result = text_trigger.findall(message)
#TODO: specify the info sent to the trigger.
else:
#trigger.fire(message, *args, **kwargs)
result = text_trigger.fire(ircm)
if result:
d = threads.deferToThread(plugin.execute, ircm, None, result)
d.addCallback(self.emitMessage)
## Main Command trigger is commonly '!'
trigger = self.factory.main_trigger
if message.startswith(trigger) or message.startswith(self.nickname):
word_list = message.split(' ')
if message.startswith(trigger):
command = word_list[0].lstrip(trigger)
elif message.startswith(self.nickname):
try:
command = word_list[1].strip()
except IndexError:
logging.warning('Invalid call: "{0}"'.format(ircm.render()))
return
## TODO: Reload should be dependant on userRole
## TODO: Localize
if command == "reload":
self.plugins_init(is_reloading=True)
return
## TODO: Consider sending the split word list.
try:
plugin = self.action_plugins[command]
except KeyError:
logging.warning("Command {0} missing".format(command))
return
if plugin.synchronous:
d = defer.maybeDeferred(plugin.execute, ircm, None)
else:
d = threads.deferToThread(plugin.execute, ircm, None)
d.addCallback(self.emitMessage)
return
def privmsg(self, user, channel, msg):
"""Gets called when the bot receives a message in a channel or via PM.
Here is contained the main logic of tio_chema. Should dispatch messages
to the plugins registered, depending if they register for a global or
a specific trigger keyword.
It blocks, so it should not include heavy or slow logic.
Args:
user: A string containing the origin user.
channel: A string with the originating channel or PM channel.
msg: A string containing the message recieved.
"""
message = IRCMessage(channel, msg, user)
#TODO: add logging
#print message
#TODO: add channel trigger plugins (user defined actions)
self._parseAndExecute(message)
class ChemaBotFactory(protocol.ClientFactory):
def __init__(self, config):
self.config = config
# TODO add multi channel support
self.channel = "#"+self.config['channel']
self.filename = self.config['log_file']
self.main_trigger = self.config['main_command_trigger']
def buildProtocol(self, addr):
p = ChemaBot(self.config['nickname'])
p.factory = self
return p
def clientConnectionLost(self, connector, reason):
"""If we get disconnected, reconnect to server."""
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "connection failed:", reason
reactor.stop()
if __name__ == '__main__':
try:
# Load the configuration file
config = ConfigObj(sys.argv[1])
# create factory protocol and application
bot_factory = ChemaBotFactory(config)
observer = log.PythonLoggingObserver()
observer.start()
reactor.connectTCP(config['irc_server'],
config.as_int('irc_port'),
bot_factory)
reactor.run()
except:
print("Usage: python bot_chema.py config_file.cf")
exit(1)