2 # -*- coding: utf-8 -*-
10 from optparse
import OptionParser
14 if sys
.version_info
< (3, 0):
16 sys
.setdefaultencoding('utf8')
20 class MUCBot(sleekxmpp
.ClientXMPP
):
21 def __init__(self
, jid
, password
, room
, nick
, rpass
):
22 sleekxmpp
.ClientXMPP
.__init
__(self
, jid
, password
)
30 self
.add_event_handler("session_start", self
.start
)
31 #self.add_event_handler("groupchat_message", self.muc_message)
32 self
.add_event_handler('message', self
.message
)
34 def start(self
, event
):
38 # Check for db.json, if empty or not there, create it.
39 if (not os
.path
.isfile("db.json") or os
.path
.getsize("db.json") == 0):
40 print("WARNING\tEvent database not found or empty, creating new one.")
41 with io
.open("db.json", "w", encoding
="utf8") as f
:
44 if (not os
.path
.isfile("users.json") or os
.path
.getsize("users.json") == 0):
45 print("WARNING\tUser database not found or empty, creating new one.")
46 with io
.open("users.json", "w", encoding
="utf8") as f
:
49 with
open("users.json") as f
:
50 self
.users
= json
.load(f
)
53 self
.plugin
['xep_0045'].joinMUC(self
.room
,
58 self
.plugin
['xep_0045'].joinMUC(self
.room
,
62 def message(self
, msg
):
63 if ((msg
['type'] in ('normal', 'chat'))
64 and (msg
['from'].bare
in self
.users
)
65 and (msg
['mucnick'] != self
.nick
)):
67 whos
= msg
['from'].bare
69 if "!ping" in msg
['body']:
70 msg
.reply("Pong!").send()
72 if "!add" in msg
['body']:
73 addargs
= msg
['body'].split('"')[1::2]
75 if (len(addargs
) != 2):
76 msg
.reply('Юзаж: !add "дата" "событие", ковычки обязательны!').send()
78 with io
.open("db.json", encoding
="utf8") as f
:
89 with io
.open('db.json', 'w', encoding
="utf8") as f
:
90 f
.write(json
.dumps(data
, sort_keys
=True, indent
=4, ensure_ascii
=False))
92 msg
.reply("Движуха добавлена.").send()
93 self
.send_message(mto
= self
.room
,
94 mbody
= "{} добавил движуху: {}".format(whos
, addargs
[0]),
97 if "!del" in msg
['body']:
98 delargs
= msg
['body'].split('"')[1::2]
100 if (len(delargs
) != 1):
101 msg
.reply('Юзаж: !del "дата", ковычки обязательны!').send()
105 with io
.open("db.json", encoding
="utf8") as f
:
108 for i
in range(len(data
)):
109 if data
[i
]["date"] == delargs
[0]:
115 with io
.open('db.json', 'w', encoding
="utf8") as f
:
116 f
.write(json
.dumps(data
, sort_keys
=True, indent
=4, ensure_ascii
=False))
117 msg
.reply("Движуха удалена.").send()
118 self
.send_message(mto
= self
.room
,
119 mbody
= "{} удалил движуху: {}".format(whos
, delargs
[0]),
122 msg
.reply("Движуха {} не найдена.".format(delargs
[0])).send()
125 if "!list" in msg
['body']:
126 with
open("db.json") as f
:
130 msg
.reply("В настоящий момент, движух нет.").send()
132 result
= "Текущий список движух:\n"
133 result
+= ("-" * 60) + "\n"
134 result
+= "{:<20} {:<20}\n".format("Дата", "Движуха")
135 result
+= ("-" * 60) + "\n"
137 for i
in range(len(data
)):
138 result
+= "{:<20} {:<20}\n".format(data
[i
]["date"], data
[i
]["event"])
139 result
+= ("-" * 60) + "\n"
141 msg
.reply(result
).send()
143 if "!help" in msg
['body']:
145 '\nДвижуха v0.3 "Почти Гамма"\n'
149 '!add "дата" "событие"\n'
150 ' Добавить новую движуху.\n\n'
152 ' Удалить движуху.\n\n'
154 'Список текущих движух.\n'
157 msg
.reply(helpstr
).send()
160 if __name__
== '__main__':
161 # Setup the command line arguments.
162 optp
= OptionParser()
164 # Output verbosity options.
165 optp
.add_option('-q', '--quiet', help='set logging to ERROR',
166 action
='store_const', dest
='loglevel',
167 const
=logging
.ERROR
, default
=logging
.INFO
)
168 optp
.add_option('-d', '--debug', help='set logging to DEBUG',
169 action
='store_const', dest
='loglevel',
170 const
=logging
.DEBUG
, default
=logging
.INFO
)
171 optp
.add_option('-v', '--verbose', help='set logging to COMM',
172 action
='store_const', dest
='loglevel',
173 const
=5, default
=logging
.INFO
)
175 # JID and password options.
176 optp
.add_option("-j", "--jid", dest
="jid",
178 optp
.add_option("-s", "--rpass", dest
="rpass",
179 help="Room password, if any.")
180 optp
.add_option("-p", "--pass", dest
="password",
181 help="password to use")
182 optp
.add_option("-r", "--room", dest
="room",
183 help="MUC room to join")
184 optp
.add_option("-n", "--nick", dest
="nick",
187 opts
, args
= optp
.parse_args()
190 logging
.basicConfig(level
=opts
.loglevel
,
191 format
='%(levelname)-8s %(message)s')
194 opts
.jid
= raw_input("Username: ")
195 if opts
.password
is None:
196 opts
.password
= getpass
.getpass("Password: ")
197 if opts
.room
is None:
198 opts
.room
= raw_input("MUC room: ")
199 if opts
.nick
is None:
200 opts
.nick
= raw_input("MUC nickname: ")
202 # Setup the MUCBot and register plugins. Note that while plugins may
203 # have interdependencies, the order in which you register them does
205 xmpp
= MUCBot(opts
.jid
, opts
.password
, opts
.room
, opts
.nick
, opts
.rpass
)
206 xmpp
.register_plugin('xep_0030') # Service Discovery
207 xmpp
.register_plugin('xep_0045') # Multi-User Chat
208 xmpp
.register_plugin('xep_0199') # XMPP Ping
210 # Connect to the XMPP server and start processing XMPP stanzas.
212 # If you do not have the dnspython library installed, you will need
213 # to manually specify the name of the server if it does not match
214 # the one in the JID. For example, to use Google Talk you would
217 # if xmpp.connect(('talk.google.com', 5222)):
219 xmpp
.process(block
=True)
222 print("Unable to connect.")