Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@TTTPOB
Created April 11, 2021 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TTTPOB/3c1e6aa533942903d9c04a29350c2ecf to your computer and use it in GitHub Desktop.
Save TTTPOB/3c1e6aa533942903d9c04a29350c2ecf to your computer and use it in GitHub Desktop.
telegram bot send message via cloudflare worker (for server notification like job done)
#!/usr/bin/env python3
from urllib import request
import sys
import json
TOKEN="16181xxxxx:xxxxxxxxxxxxxxx"
CHAT="-100118639xxxx"
TEXT=sys.argv[1]
SERVER="what ever name you want"
URL="https://yourworker.address"
content={
"TOKEN":TOKEN,
"CHATID":CHAT,
"TEXT":"server: "+SERVER+"\n\n"+TEXT
}
content=json.dumps(content).encode(encoding="utf-8")
headers={'Content-Type': 'application/json','User-Agent':'fake'}
req=request.Request(url=URL,data=content,headers=headers)
print(request.urlopen(req).read().decode(encoding='utf-8'))
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond with hello worker text
* @param {Request} request
*/
async function handleRequest(request) {
// if (typeof request.body === 'object'){
// msg=request.body
// }else if (typeof request.body === 'string'){
// msg=JSON.parse(request.body)
// }
// msg=msg.json();
msg=await request.json()
const bot_url="https://api.telegram.org/bot"+msg.TOKEN+"/sendMessage";
const messageSend=JSON.stringify(
{"chat_id":msg.CHATID, "text": msg.TEXT}
);
try{
let response=fetch(bot_url,{method:'POST',headers:{"Content-Type":"application/json"},body:messageSend});
return await response;
}catch(error){
return new Response("Error when sending notification")
}
return new Response(messageSend, {
headers: { 'content-type': 'text/plain' },
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment