Skip to content

Instantly share code, notes, and snippets.

@nonamenix
Created October 16, 2016 10:48
Show Gist options
  • Save nonamenix/4fc4484a7a9a6595a24d578669ebe0a5 to your computer and use it in GitHub Desktop.
Save nonamenix/4fc4484a7a9a6595a24d578669ebe0a5 to your computer and use it in GitHub Desktop.
GreatFuckingAdvice Telegram Bot
from aiotg import Bot, aiohttp
from utils import html_decode
bot = Bot(api_token="***")
advice_api_url = "http://fucking-great-advice.ru/api/{}"
sound_url = 'http://fucking-great-advice.ru/files/sounds/{}' # sound_9.MP3
class Advice:
def __init__(self, id, text, sound, stat=0):
self._id = id
self.text = text
self.sound = sound
self.stat = stat
async def get_random_advice():
async with aiohttp.ClientSession() as session:
async with session.get(advice_api_url.format('random')) as resp:
return Advice(**(await resp.json()))
async def get_latest_advices(n=1):
async with aiohttp.ClientSession() as session:
async with session.get(advice_api_url.format('latest')) as resp:
body = (await resp.json())
return map(lambda a: Advice(**a), body)
@bot.command(r"/advice")
@bot.command(r"/random")
@bot.command(r"совет")
async def random(chat, match):
advice = await get_random_advice()
return await chat.send_text(html_decode(advice.text))
@bot.command(r'/latest')
async def latest(chat, match):
advices = list(await get_latest_advices())
return await chat.send_text(html_decode(advices[0].text))
@bot.command(r'/sound')
async def sound(chat, match):
await chat.send_chat_action('record_audio')
advice = await get_random_advice()
await chat.send_text(sound_url.format(advice.sound))
bot.run()
code_mapping = (
("'", '''),
('"', '"'),
('>', '>'),
('<', '&lt;'),
(' ', '&nbsp;'),
('—', '&#151;'),
('&', '&amp;'),
)
def html_decode(s):
for code, escaped in code_mapping:
s = s.replace(escaped, code)
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment