Skip to content

Instantly share code, notes, and snippets.

@ysc3839
Created February 5, 2017 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ysc3839/3e8c20d41fefcad70327764e2ca81862 to your computer and use it in GitHub Desktop.
Save ysc3839/3e8c20d41fefcad70327764e2ca81862 to your computer and use it in GitHub Desktop.
Telegram translate bot
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=I0011,C0111,C0103
from __future__ import print_function
import threading
import telepot
from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent
from goslate import Goslate
def find_between(s, first, last):
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return ""
def on_chat_message(msg):
content_type, _, chat_id = telepot.glance(msg, flavor='chat')
if content_type == 'text':
bot.sendMessage(chat_id, '新年快乐!')
def on_inline_query(msg):
def compute():
_, _, query_string = telepot.glance(msg, flavor='inline_query')
print('Inline Query:', query_string)
if query_string:
try:
print('Start translate')
gs = Goslate()
translate_result = gs.translate(query_string, 'zh')
print(translate_result)
results = [InlineQueryResultArticle(
id='translate',
title='翻译结果',
description=translate_result,
input_message_content=InputTextMessageContent(
message_text=translate_result
))]
except:
threading.currentThread().cancel()
return
else:
results = [InlineQueryResultArticle(
id='usage',
title='使用说明',
description='输入你想翻译的文本',
input_message_content=InputTextMessageContent(
message_text='输入你想翻译的文本'
))]
return (results, 3600 * 2) # (results, cache_time)
answerer.answer(msg, compute)
def on_chosen_inline_result(msg):
result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
print('Chosen Inline Result:', result_id, from_id, query_string)
if __name__ == '__main__':
TOKEN = ''
bot = telepot.Bot(TOKEN)
answerer = telepot.helper.Answerer(bot)
bot.message_loop({'chat': on_chat_message,
'inline_query': on_inline_query,
'chosen_inline_result': on_chosen_inline_result},
run_forever='Running...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment