Forgot to clean some debug code before last commit.
[DvizhuhaBot.git] / dvizhuha.py
blobdae6807eee510fdaae7874e79deab7af2b3054db
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
4 import sys
5 import logging
6 import getpass
7 import json
8 import io
9 import os
10 from optparse import OptionParser
12 import sleekxmpp
14 if sys.version_info < (3, 0):
15 reload(sys)
16 sys.setdefaultencoding('utf8')
17 else:
18 raw_input = input
20 class MUCBot(sleekxmpp.ClientXMPP):
21 def __init__(self, jid, password, room, nick, rpass):
22 sleekxmpp.ClientXMPP.__init__(self, jid, password)
24 self.room = room
25 self.nick = nick
26 self.rpass = rpass
28 self.users = {}
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):
35 self.get_roster()
36 self.send_presence()
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:
42 f.write("[]")
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:
47 f.write("[]")
49 with open("users.json") as f:
50 self.users = json.load(f)
52 if (self.rpass):
53 self.plugin['xep_0045'].joinMUC(self.room,
54 self.nick,
55 password=self.rpass,
56 wait=True)
57 else:
58 self.plugin['xep_0045'].joinMUC(self.room,
59 self.nick,
60 wait=True)
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()
77 else:
78 with io.open("db.json", encoding="utf8") as f:
79 data = json.load(f)
81 add_dict = {
82 'date' : addargs[0],
83 'event' : addargs[1],
84 'by' : whos
87 data.append(add_dict)
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]),
95 mtype = 'groupchat')
97 if "!del" in msg['body']:
98 delargs = msg['body'].split('"')[1::2]
100 if (len(delargs) != 1):
101 msg.reply('Юзаж: !del "дата", ковычки обязательны!').send()
103 else:
104 deleted = False
105 with io.open("db.json", encoding="utf8") as f:
106 data = json.load(f)
108 for i in range(len(data)):
109 if data[i]["date"] == delargs[0]:
110 data.pop(i)
111 deleted = True
112 break
114 if (deleted):
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]),
120 mtype = 'groupchat')
121 else:
122 msg.reply("Движуха {} не найдена.".format(delargs[0])).send()
125 if "!list" in msg['body']:
126 with open("db.json") as f:
127 data = json.load(f)
129 if (data == []):
130 msg.reply("В настоящий момент, движух нет.").send()
131 else:
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']:
144 helpstr = (
145 '\nДвижуха v0.3 "Почти Гамма"\n'
146 'Комманды:\n'
147 '!ping\n'
148 ' Очевидно же.\n\n'
149 '!add "дата" "событие"\n'
150 ' Добавить новую движуху.\n\n'
151 '!del "дата"\n'
152 ' Удалить движуху.\n\n'
153 '!list\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",
177 help="JID to use")
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",
185 help="MUC nickname")
187 opts, args = optp.parse_args()
189 # Setup logging.
190 logging.basicConfig(level=opts.loglevel,
191 format='%(levelname)-8s %(message)s')
193 if opts.jid is None:
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
204 # not matter.
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.
211 if xmpp.connect():
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
215 # need to use:
217 # if xmpp.connect(('talk.google.com', 5222)):
218 # ...
219 xmpp.process(block=True)
220 print("Done")
221 else:
222 print("Unable to connect.")