/
chat.py
294 lines (246 loc) · 7.99 KB
/
chat.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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#!/sevabot
# -*- coding: utf-8 -*-
#http://skype4py.sourceforge.net/doc/html/Skype4Py.utils-pysrc.html#CachedCollection.Item
from __future__ import unicode_literals
import sys
# sys.path.append('~/sevabot/libs/pygoogle.py')
import os
import re
import logging
# import requests
from bs4 import BeautifulSoup
import urllib2
import logging
import datetime
import random
from time import gmtime, strftime
# import html2text
# from pygoogle import pygoogle
import pickle
from collections import OrderedDict
from sevabot.bot.stateful import StatefulSkypeHandler
from sevabot.utils import ensure_unicode, get_chat_id
import Skype4Py
BOT_NAME = "alex"
logger = logging.getLogger("TessChat")
logger.setLevel(logging.DEBUG)
# logger.setLevel(logging.INFO)
logger.debug("Tess Chat module level load import")
class TessChat(StatefulSkypeHandler):
"""
Print help text to chat.
"""
def init(self, sevabot):
"""
Print help text to chat.
"""
self.skype = sevabot.getSkype()
self.sevabot = sevabot
self.commands = {
"деплой": self.cmd_deploy,
"время": self.cmd_time,
"загугли": self.cmd_search,
"(привет|hi|здаров)": self.cmd_hi,
"что такое": self.cmd_what_is,
"стреляй": self.cmd_shut,
"(man|help)": self.cmd_man,
}
self.publickcommands = {
"(привет|hi|здаров)": self.cmd_hi,
}
def handle_message(self, msg, status):
"""
Print help text to chat.
"""
if status == 'SENT':
return True
body = ensure_unicode(msg.Body)
lower = body.lower()
words = re.split('(\s+|\n|,)', lower, flags=re.M)
if len(words) < 2:
return False
if False==words[0].startswith(BOT_NAME):
return False
chat_id = get_chat_id(msg.Chat)
# usrs = msg.Chat.Members
# aUm = iter(usrs)
# for i, x in enumerate(usrs):
# msg.Chat.SendMessage(" - %s" % x.FullName)
# Check if we match any of our commands
for name, cmd in self.commands.items():
patern = re.compile(name)
if patern.search(lower) != None:
cmd(msg, chat_id)
return True
return False
def shutdown(self):
"""
Print help text to chat.
"""
def register_callback(self, skype, event, callback):
"""
Print help text to chat.
"""
return skype.RegisterEventHandler(event, callback)
def unregister_callback(self, skype, event, callback):
"""
Print help text to chat.
"""
return skype.UnregisterEventHandler(event, callback)
# @staticmethod
def get_link_title(e,url):
"""
Print help text to chat.
"""
try:
content = urllib2.urlopen(url).read()
soup = BeautifulSoup(content)
return soup.title.string
except:
return None
def cmd_man(self, msg, chat_id):
"""
Print help text to chat.
"""
string = """Умею:
!dice,
!ping,
!sad,
!weather,
деплой,
время,
привет,
что такое <string>?,
стреляй,
man"""
msg.Chat.SendMessage(string)
def cmd_deploy(self, msg, chat_id):
"""
Print help text to chat.
"""
msg.Chat.SendMessage("деплою потихоньку...")
def cmd_time(self, msg, chat_id):
"""
Print help text to chat.
"""
msg.Chat.SendMessage("%s" % strftime("%Y-%m-%d %H:%M:%S", gmtime()))
def cmd_search(self, msg, chat_id):
"""
Print help text to chat.
"""
msg.Chat.SendMessage("ничего не нашел")
def cmd_hi(self, msg, chat_id):
"""
Print help text to chat.
"""
# self.hi_file = os.path.join(os.path.dirname(__file__), "hi.tmp")
# self.hi_history = Hihistory.read(self.hi_file)
msg.Chat.SendMessage("%s, привет!" % msg.FromDisplayName);
def cmd_shut(self, msg, chat_id):
"""
Print help text to chat.
"""
random.seed()
usrs = msg.Chat.Members
index = random.randint(0, usrs.Count-1)
user = usrs[index]
msg.Chat.SendMessage("%s убит! (yn) " % user.FullName)
# aUm = iter(usrs)
# for i, x in enumerate(usrs):
# msg.Chat.SendMessage(" - %s" % x.FullName)
def cmd_what_is(self, msg, chat_id):
"""
Print help text to chat.
"""
# search = re.compile('(?<=что такое\s).\w+')
# search = re.compile('(?<=что такое\s)[^\s]*')
search = re.compile('(?<=что такое\s)[^?]*')
#
body = ensure_unicode(msg.Body)
lower = body.lower()
whatis_text = search.findall(lower)
if whatis_text!=None:
new_url = "http://ru.wikipedia.org/wiki/"+whatis_text[0].replace (" ", "_")
msg.Chat.SendMessage("глянь тут %s" % new_url)
# str_wiki = self.get_wiki_text(new_url)
# msg.Chat.SendMessage("%s" % str_wiki)
# if str_wiki!=None:
# msg.Chat.SendMessage("%s" % str_wiki)
# def get_wiki_text(e,url):
# """
# Print help text to chat.
# """
# rez = "None1"
# content = urllib2.urlopen(url).read()
# soup = BeautifulSoup(content)
# div = soup.find("div", {"id": "mw-content-text "})
# rez = div
# return rez
# try:
# content = urllib2.urlopen(url).read()
# soup = BeautifulSoup(content)
# # div = soup.find("div", {"id": "noarticletext"})
# # if div!=None:
# # return None
# div = soup.find("div", {"id": "mw-content-text "})
# # rez = div.first('p').renderContents()
# rez = div.renderContents()
# # .contents[0]
# # h = html2text.HTML2Text()
# # h.ignore_links = True
# # print h.handle("<p>Hello, <a href='http://earth.google.com/'>world</a>!")
# # return soup.title.string
# except:
# rez = "EEER"
# return rez
# class Hihistory:
# """
# Stored pickled state of the tasks.
# Use Python pickling serialization for making status info persistent.
# """
# def __init__(self):
# # Chat id -> OrderedDict() of jobs mappings
# self.records = dict()
# @classmethod
# def read(cls, path):
# """
# Read status file.
# Return fresh status if file does not exist.
# """
# if not os.path.exists(path):
# # Status file do not exist, get default status
# return Hihistory()
# f = open(path, "rb")
# try:
# return pickle.load(f)
# finally:
# f.close()
# @classmethod
# def write(cls, path, status):
# """
# Write status file
# """
# f = open(path, "wb")
# pickle.dump(status, f)
# f.close()
# def get_tasks(self, chat_id):
# """
# Get jobs of a particular chat.
# """
# if not chat_id in self.records:
# # Skype username -> Task instance mappings
# self.records[chat_id] = OrderedDict()
# return self.records[chat_id]
# class Rec:
# """
# """
# def __init__(self, real_name, started, desc):
# """
# """
# self.chat_id = started
# self.user_id = desc
# # The following has been
# # ripped off from https://github.com/imtapps/django-pretty-times/blob/master/pretty_times/pretty.py
# Export the instance to Sevabot
sevabot_handler = TessChat()
__all__ = ['sevabot_handler']