Created
February 11, 2025 02:30
-
-
Save Liki4/f0f86f3cee57f8fdaadc2926801b60aa to your computer and use it in GitHub Desktop.
cmd5 telegram webhook bot deploy on cloudflare
This file contains hidden or 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
/** | |
* https://github.com/cvzi/telegram-bot-cloudflare | |
*/ | |
const TOKEN = ENV_BOT_TOKEN // Get it from @BotFather https://core.telegram.org/bots#6-botfather | |
const WEBHOOK = '/endpoint' | |
const SECRET = ENV_BOT_SECRET // A-Z, a-z, 0-9, _ and - | |
const EMAIL = ENV_CMD5_EMAIL | |
const KEY = ENV_CMD5_KEY | |
/** | |
* Wait for requests to the worker | |
*/ | |
addEventListener('fetch', event => { | |
const url = new URL(event.request.url) | |
if (url.pathname === WEBHOOK) { | |
event.respondWith(handleWebhook(event)) | |
} else if (url.pathname === '/registerWebhook') { | |
event.respondWith(registerWebhook(event, url, WEBHOOK, SECRET)) | |
} else if (url.pathname === '/unRegisterWebhook') { | |
event.respondWith(unRegisterWebhook(event)) | |
} else { | |
event.respondWith(new Response('No handler for this request')) | |
} | |
}) | |
/** | |
* Handle requests to WEBHOOK | |
* https://core.telegram.org/bots/api#update | |
*/ | |
async function handleWebhook (event) { | |
// Check secret | |
if (event.request.headers.get('X-Telegram-Bot-Api-Secret-Token') !== SECRET) { | |
return new Response('Unauthorized', { status: 403 }) | |
} | |
// Read request body synchronously | |
const update = await event.request.json() | |
// Deal with response asynchronously | |
event.waitUntil(onUpdate(update)) | |
return new Response('Ok') | |
} | |
/** | |
* Handle incoming Update | |
* https://core.telegram.org/bots/api#update | |
*/ | |
async function onUpdate (update) { | |
if ('message' in update) { | |
await onMessage(update.message) | |
// } else if ('inline_query' in update) { | |
// await onInlineQuery(update.inline_query) | |
} | |
} | |
/** | |
* Handle incoming Message | |
* https://core.telegram.org/bots/api#message | |
*/ | |
function onMessage (message) { | |
const whiteList = [123456, 234567, -10345678]; // Telegram userId or groupId | |
const splt = message.text.indexOf(' '); | |
const cmd = message.text.slice(0, splt); | |
const arg = message.text.slice(splt + 1); | |
if (!(whiteList.includes(message.chat.id))) { | |
sendPlainReplyText(message.chat.id, message.message_id, "chat id not in whitelist"); | |
return setMessageReaction(message, '🤡') | |
} | |
if ((splt !== -1) && ((cmd ==='/cmd5') || (cmd === '/cmd5@Liki4s_cmd5_bot') )) { | |
return fetchCmd5(EMAIL, KEY, arg).then(data => { | |
if (data.startsWith("CMD5-ERROR")) { | |
var err; | |
switch(data) { | |
case 'CMD5-ERROR:0': | |
err = "解密失败"; | |
break; | |
case 'CMD5-ERROR:-1': | |
err = "无效的用户名密码"; | |
break; | |
case 'CMD5-ERROR:-2': | |
err = "余额不足"; | |
break; | |
case 'CMD5-ERROR:-3': | |
err = "解密服务器故障"; | |
break; | |
case 'CMD5-ERROR:-4': | |
err = "不识别的密文"; | |
break; | |
case 'CMD5-ERROR:-7': | |
err = "不支持的类型"; | |
break; | |
case 'CMD5-ERROR:-8': | |
err = "api权限被禁止"; | |
break; | |
case 'CMD5-ERROR:-9': | |
err = "条数超过100条"; | |
break; | |
default: | |
err = "不知道是什么错误反正爆了"; | |
} | |
sendPlainReplyText(message.chat.id, message.message_id, err); | |
return setMessageReaction(message, '💩') | |
} | |
sendPlainReplyText(message.chat.id, message.message_id, data); | |
return setMessageReaction(message, '👌') | |
}) | |
} | |
if (message.text.startsWith("/cmd5")) { | |
sendPlainReplyText(message.chat.id, message.message_id, "Usage: /cmd5 <hash>"); | |
return setMessageReaction(message, '🤓') | |
} | |
// sendPlainReplyText(message.chat.id, message.message_id, JSON.stringify(message.message_id, null, 2)); | |
// return setMessageReaction(message, '🖕') | |
return | |
} | |
/** | |
* Send plain text message | |
* https://core.telegram.org/bots/api#sendmessage | |
*/ | |
async function sendPlainReplyText (chatId, messageId, text) { | |
return (await fetch(apiUrl('sendMessage', { | |
chat_id: chatId, | |
text: text, | |
reply_parameters: JSON.stringify({ | |
chat_id: chatId, | |
message_id: messageId | |
}) | |
}))).json() | |
} | |
/** | |
* Set Message Reaction | |
* https://core.telegram.org/bots/api#setmessagereaction | |
*/ | |
async function setMessageReaction (message, reaction) { | |
const reaction_ = [] | |
const emoji = reaction | |
reaction_.push({ | |
type: 'emoji', | |
emoji | |
}) | |
return (await fetch(apiUrl('setMessageReaction', { | |
chat_id: message.chat.id, | |
message_id: message.message_id, | |
reaction: JSON.stringify(reaction_), | |
is_big: false | |
}))).json() | |
} | |
async function fetchCmd5(email, key, hash) { | |
const url = `http://www.cmd5.com/api.ashx?email=${email}&key=${key}&hash=${hash}`; | |
try { | |
const response = await fetch(url); | |
if (!response.ok) { | |
throw new Error(`HTTP error! Status: ${response.status}`); | |
} | |
const data = await response.text(); | |
return data; | |
} catch (error) { | |
console.error('Fetch error:', error); | |
} | |
} | |
/** | |
* Set webhook to this worker's url | |
* https://core.telegram.org/bots/api#setwebhook | |
*/ | |
async function registerWebhook (event, requestUrl, suffix, secret) { | |
// https://core.telegram.org/bots/api#setwebhook | |
const webhookUrl = `${requestUrl.protocol}//${requestUrl.hostname}${suffix}` | |
const r = await (await fetch(apiUrl('setWebhook', { url: webhookUrl, secret_token: secret }))).json() | |
return new Response('ok' in r && r.ok ? 'Ok' : JSON.stringify(r, null, 2)) | |
} | |
/** | |
* Remove webhook | |
* https://core.telegram.org/bots/api#setwebhook | |
*/ | |
async function unRegisterWebhook (event) { | |
const r = await (await fetch(apiUrl('setWebhook', { url: '' }))).json() | |
return new Response('ok' in r && r.ok ? 'Ok' : JSON.stringify(r, null, 2)) | |
} | |
/** | |
* Return url to telegram api, optionally with parameters added | |
*/ | |
function apiUrl (methodName, params = null) { | |
let query = '' | |
if (params) { | |
query = '?' + new URLSearchParams(params).toString() | |
} | |
return `https://api.telegram.org/bot${TOKEN}/${methodName}${query}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment