Skip to content

Instantly share code, notes, and snippets.

@bingluen
Created June 20, 2017 23:08
Show Gist options
  • Save bingluen/2662f0b544e729a76f3a978956efdd7f to your computer and use it in GitHub Desktop.
Save bingluen/2662f0b544e729a76f3a978956efdd7f to your computer and use it in GitHub Desktop.
Telegram Chat Bot Sample
{
"bot_token": "",
"webhook": {
"url": "",
"certificate": "",
"max_connections": 40,
"allowed_updates": ["message"],
"port": 88
}
}
import json
import requests
import re
import SocketServer
API_BASE = 'https://api.telegram.org/bot'
CONFIG = {}
def init(configSource = 'config.json'):
with open(configSource) as configFile:
CONFIG = json.load(configFile)
API_BASE = API_BASE + CONFIG['bot_token'] + '/'
def setWebhook(webhookSetting):
requestHeaders = {
'content-type': 'application/json'
}
payload = {
'url': CONFIG['webhook']['url'],
'certificate': CONFIG['webhook']['certificate'],
'max_connections': CONFIG['webhook']['max_connections'],
'allowed_updates': CONFIG['webhook']['allowed_updates']
}
requests.POST(
API_BASE + 'setWebhook',
headers = requestHeaders,
data = json.dumps(payload)
)
def sendMessage(payload):
requestHeaders = {
'content-type': 'application/json'
}
requests.POST(
API_BASE + 'sendMessage',
headers = requestHeaders,
data = json.dumps(payload)
)
def handleWebhook(updateObject):
Msgfrom = updateObject['message']['from']
date = update['message']['date']
content = updateObject['message']['text']
keyword = ['你傻', '你好']
phrases = [phrase for phrase in re.split('\W+', content) if phrase in keyword]
responseMapping = {
'你傻': '你才傻www',
'你好': '你好啊^_^'
}
responseMsg = ''
for phrase in phrases:
if len (response) > 0:
responseMsg = responseMsg + '\n'
responseMsg = responseMsg + responseMapping[phrase]
payload = {
'chat_id': Msgfrom['id'],
'text': response
}
sendMessage(payload)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment