forked from szastupov/whatisbot
/
main.py
119 lines (86 loc) · 2.92 KB
/
main.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
import logging
import asyncio
import aioredis
import aiohttp
import os
import json
from aiotg import TgBot
with open("config.json") as cfg:
config = json.load(cfg)
bot = TgBot(**config)
logger = logging.getLogger("WhatisBot")
redis = None
async def search_wiki(text, lang="en"):
url = "https://{0}.wikipedia.org/w/api.php".format(lang)
params = {
'titles': text,
'action': 'query',
'exintro': '',
'format': 'json',
'prop': 'extracts',
'explaintext': '',
'redirects': ''
}
response = await aiohttp.get(url, params=params)
assert response.status == 200
return (await response.json())
async def wiki(chat, text, lang=None, not_found="I don't know :("):
plang = (await redis.hget(chat.sender["id"], "lang")) or "en"
if not lang:
lang = plang
if lang != plang:
await redis.hset(chat.sender["id"], "lang", lang)
logger.info("%s:\t%s (%s)", chat.sender, text, lang)
wiki = await search_wiki(text, lang)
pages = wiki["query"]["pages"]
for pid, page in pages.items():
if pid == '-1':
return (await chat.reply(not_found))
title = page["title"].replace(" ", "_")
wiki_link = "https://{0}.wikipedia.org/wiki/{1}".format(lang, title)
result = "{0}\n{1}".format(page['extract'], wiki_link)
await chat.reply(result)
@bot.command(r"/?(whatis|what is|who is|define|wiki) ([^\?]+)\??")
def wiki_en(chat, match):
return wiki(chat, match.group(2), "en")
@bot.command(r"/?(что такое|что за|опредиление|вики|кто такой) ([^\?]+)\??")
def wiki_ru(chat, match):
return wiki(chat, match.group(2), "ru", "Не знаю :(")
@bot.command(r"/?(que es|qué es|que significa|qué significa|quien es|quién es) ([^\?]+)\??")
def wiki_es(chat, match):
return wiki(chat, match.group(2), "es", "No sé :(")
@bot.command(r"/?(was ist|wo ist) ([^\?]+)\??")
def wiki_de(chat, match):
return wiki(chat, match.group(2), "de", "Nicht wissen :(")
@bot.command("(/start|/?help)")
def usage(chat, match):
text = """
Hi! I can search Wikipedia for you and your chat friends.
Here is how you can talk to me:
/define independence
/whatis love
what is love
who is Nikola Tesla?
что такое счастье
что за черт?
que es tequila
was ist liebe?
Created by @stepanz
If you like this bot, please rate it at: https://telegram.me/storebot?start=whatisbot
"""
return chat.reply(text)
@bot.default
def default(chat, message):
return wiki(chat, message["text"])
async def main():
global redis
host = os.environ.get('REDIS_HOST', 'localhost')
redis = await aioredis.create_redis((host, 6379), encoding="utf-8")
await bot.loop()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
bot.stop()