Created
December 17, 2015 14:23
-
-
Save dobrokot/bad948b020e8708fc987 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import logging | |
import telegram | |
from time import sleep | |
try: | |
from urllib.error import URLError | |
except ImportError: | |
from urllib2 import URLError # python 2 | |
import urllib | |
import re | |
def get_rythm(msg): | |
url = 'http://rifma-online.ru/rifma/' + urllib.quote(msg) + '/' | |
data = urllib.urlopen(url).read() | |
#data = open('xxx.html').read() | |
result = [] | |
for l in data.splitlines(): | |
m = re.search('<li><a href=".*>(.*)</a></li>', l) | |
if m: | |
result.append(m.group(1)) | |
return result[0:3] | |
def main(): | |
# Telegram Bot Authorization Token | |
bot = telegram.Bot('< TOKEN >') | |
# get the first pending update_id, this is so we can skip over it in case | |
# we get an "Unauthorized" exception. | |
try: | |
update_id = bot.getUpdates()[0].update_id | |
except IndexError: | |
update_id = None | |
logging.basicConfig( | |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
while True: | |
try: | |
update_id = echo(bot, update_id) | |
except telegram.TelegramError as e: | |
# These are network problems with Telegram. | |
if e.message in ("Bad Gateway", "Timed out"): | |
sleep(1) | |
elif e.message == "Unauthorized": | |
# The user has removed or blocked the bot. | |
update_id += 1 | |
else: | |
raise e | |
except URLError as e: | |
# These are network problems on our end. | |
sleep(1) | |
def echo(bot, update_id): | |
# Request updates after the last update_id | |
for update in bot.getUpdates(offset=update_id, timeout=10): | |
# chat_id is required to reply to any message | |
chat_id = update.message.chat_id | |
update_id = update.update_id + 1 | |
message = update.message.text | |
if message: | |
words = message.split() | |
if words and words[-1]: | |
word = words[-1].lower() | |
result = '; '.join(get_rythm(word.encode('UTF-8'))) | |
print repr(result) | |
# Reply to the message | |
bot.sendMessage(chat_id=chat_id, | |
text=result) | |
return update_id | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment