Skip to content

Instantly share code, notes, and snippets.

@behnamonline
Created January 25, 2025 07:22
Show Gist options
  • Save behnamonline/7abd60dfa2f1af8ddfd7bba0a5c4063b to your computer and use it in GitHub Desktop.
Save behnamonline/7abd60dfa2f1af8ddfd7bba0a5c4063b to your computer and use it in GitHub Desktop.
force join telegram bot
// ozv ejbari telegram bot
/*
https://www.instagram.com/behnamonline
https://www.youtube.com/@behnamonline
https://t.me/behnamonline99
https://www.aparat.com/behnam.online
*/
/*
1.go to D1->Console and run these 3 sql to create tables
CREATE TABLE posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT NOT NULL, from_chat_id TEXT NOT NULL, channels TEXT NOT NULL, caption TEXT NOT NULL );
2.create a KV and bind to your worker -> bot_values_link
3.create a D1 database and bind it to your worker -> dblink
4.open the worker in browser and -> https://yourworker.username.workers.dev/init to set webhook
*/
const BOT_TOKEN = '5643215646:AAOIOIRJGGAJFISLKSDFhb5GodsfuJ5'; // token robot az bot father
const ADMINS = ["Bhnm99", "admin2"]; // ID admin ha bedone @
const BOT_ID = "ozviatbottbot"; // ID robot bedone @
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const botValues = env.bot_values_link; // create a KV and bind to your worker -> bot_values_link
const botDB = env.dblink; // create a D1 database and bind it to your worker -> dblink
async function postReq(url, fields) {
const tgFormData = new FormData();
fields.forEach(obj => {
for (let key in obj) {
tgFormData.append(key, obj[key]);
}
});
const telegramResponse = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/${url}`, {
method: 'POST',
body: tgFormData,
});
return await telegramResponse;
}
// Check if the path is /init
if (url.pathname === "/init") {
try {
// Call the Telegram API to set the webhook
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const webhookkey = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
await botValues.put("webhookkey", webhookkey)
const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/setWebhook`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
url: `${url.protocol}//${url.hostname}/hook/${webhookkey}` // Use the current Worker URL
})
});
// Check if the response from Telegram is successful
const result = await response.json();
if (result.ok) {
return new Response("Webhook successfully set!", { status: 200 });
} else {
return new Response(`Failed to set webhook: ${result.description}`, { status: 400 });
}
} catch (error) {
return new Response(`Error setting webhook: ${error.message}`, { status: 500 });
}
}
if (url.pathname.startsWith("/hook")) {
const reqHook = url.pathname.split('/hook/')[1];
if (reqHook == await botValues.get("webhookkey")) {
if (request.method === "POST") {
try {
const body = await request.json();
/**/
const checkMember = async (chatId, postid) => {
const requestPost = await botDB.prepare(`SELECT * FROM posts WHERE id = ?`).bind(postid).first();
const channels = requestPost.channels.trim().split('\n').map(line => {
const [id, ...titleParts] = line.split(' ');
return { id, title: titleParts.join(' ') };
});
let isMember = [];
for (const channel of channels) {
try {
const check_member = await postReq(`getChatMember`, [
{ "chat_id": channel.id },
{ "user_id": chatId, }
]);
const check_member_json = await check_member.json();
if (check_member_json.result.status == "member" || check_member_json.result.status == "creator") {
isMember.push(channel.id)
}
} catch (e) {
}
}
let result = false;
if (channels.length > 0 && channels.length == isMember.length) {
await postReq(`copyMessage`, [
{ "chat_id": chatId },
{ "from_chat_id": requestPost.from_chat_id },
{ "message_id": requestPost.message_id }
]);
try {
await postReq(`deleteMessage`, [
{ "chat_id": chatId },
{ "message_id": await botValues.get("registerMsg_" + chatId) }
]);
} catch (e) {
// :D
}
result = true;
} else {
const mustJoin = [];
for (const channel of channels) {
if (!isMember.includes(channel.id)) {
mustJoin.push([{
"text": channel.title,
"url": `https://t.me/${channel.id.replace(/^@+/, '')}`
}])
}
}
mustJoin.push([{
"text": "✅ عضو شدم بررسی",
"callback_data": postid
}])
const mustJoinBtns = JSON.stringify({
"inline_keyboard":
mustJoin
});
let registerMsgSent = true;
if (await botValues.get("registerMsg_" + chatId)) {
const editMessageResponse = await postReq(`editMessageReplyMarkup`, [
{ "chat_id": chatId },
{ "message_id": await botValues.get("registerMsg_" + chatId) },
{ "reply_markup": mustJoinBtns }
]);
const editMessageResponseJson = await editMessageResponse.json();
if (!editMessageResponseJson.ok && editMessageResponseJson.description.toLowerCase().includes("not found")) {
registerMsgSent = false;
}
} else {
registerMsgSent = false;
}
if (!registerMsgSent) {
const postCaption = JSON.parse(requestPost.caption);
let registerMsg = null;
const start_cap = "برای دریافت این باید در همه ی کانال های زیر 👇 عضو بشی و روی بررسی کلیک کنی";
if (postCaption.type == 'text') {
registerMsg = await postReq(`sendMessage`, [
{ "chat_id": chatId },
{ "text": postCaption.text+"\n\n"+start_cap },
{ "reply_markup": mustJoinBtns }
]);
} else {
registerMsg = await postReq(`copyMessage`, [
{ "chat_id": chatId },
{ "from_chat_id": requestPost.from_chat_id },
{ "message_id": postCaption.message_id },
{ "caption": postCaption.text+"\n\n"+start_cap},
{ "reply_markup": mustJoinBtns }
]);
}
/**/
const registerMsgJson = await registerMsg.json();
await botValues.put("registerMsg_" + chatId, registerMsgJson.result.message_id)
}
}
return result;
}
if (body.callback_query) {
const callbackQuery = body.callback_query;
const is_registerd = await checkMember(callbackQuery.message.chat.id, callbackQuery.data)
if (!is_registerd) {
await postReq(`answerCallbackQuery`, [
{ "callback_query_id": callbackQuery.id },
{ "text": "هنوز تو همشون عضو نشدی 🫤" },
{ "show_alert": true },
]);
} else {
await postReq(`answerCallbackQuery`, [
{ "callback_query_id": callbackQuery.id }
]);
}
}
if (body.message) {
const chatId = body.message.chat.id;
if (ADMINS.includes(body.message.chat.username)) {
await postReq(`setMyCommands`, [
{
"scope": JSON.stringify({
type: 'chat', // Scope type (e.g., 'chat', 'default', 'chat_member')
chat_id: chatId // Chat ID where commands apply
})
},
{ "commands": JSON.stringify([{ command: '/newpost', description: 'پست جدید' }]) }])
const setAct = async (act) => {
await botValues.put("action_" + chatId, JSON.stringify(act))
}
if (body.message.text == '/newpost') {
await postReq(`sendMessage`, [
{ "chat_id": chatId },
{ "text": "یه چیزی ارسال کنید متن ، فایل ، ویس ، هرچی ..." },])
await setAct({ "act": "wait_for_post" });
} else if (('text' in body.message && !body.message.text.startsWith("/start")) || !('text' in body.message)) {
try {
const command = JSON.parse(await botValues.get("action_" + chatId))
if (command.act == "wait_for_post") {
command["message_id"] = body.message.message_id
command["act"] = "wait_for_channels"
await setAct(command);
await postReq(`sendMessage`, [
{ "chat_id": chatId },
{ "text": "کانال های عضو اجباری را وارد کنید" + "\n" + "به این صورت\n\n@channelID1 title1\n@channelID2 title2" },
])
} else if (command.act == "wait_for_channels") {
await postReq(`sendMessage`, [
{ "chat_id": chatId },
{ "text": "عنوان را وارد کنید" },
])
command["channels"] = body.message.text
command["act"] = "wait_for_caption"
await setAct(command);
} else if (command.act == "wait_for_caption") {
let caption = {};
if ('caption' in body.message) {
caption = {
type: "file_with_caption",
message_id: body.message.message_id,
text: body.message.caption
}
} else if ('text' in body.message) {
caption = {
type: "text",
text: body.message.text
}
} else {
caption = {
type: "file_without_caption",
message_id: body.message.message_id,
text: ""
}
}
const insertNewPost = await botDB.prepare(`INSERT INTO posts (message_id, from_chat_id, channels, caption) VALUES (?1, ?2, ?3, ?4)`).bind(
String(command["message_id"]),
String(chatId),
String(command["channels"]),
String(JSON.stringify(caption)),
).run();
const postCaption = "برای دریافت باید عضو"+body.message.text
const buyBtn = JSON.stringify({
"inline_keyboard": [
[
{
"text": "دریافت فایل",
"url": `https://t.me/${BOT_ID}?start=${insertNewPost.meta.last_row_id}`
}
]
]
});
await postReq(`copyMessage`, [
{ "chat_id": chatId },
{ "from_chat_id": chatId },
{ "message_id": body.message.message_id },
{ "reply_markup": buyBtn }
]);
await setAct({ "act": "idle" });
/**/
}
} catch (e) {
}
}
}
if (body.message.text.startsWith("/start")) {
const postid = body.message.text.match(/\/start (\w+)/)[1];
if (postid) {
await botValues.put("registerMsg_" + chatId, "")
}
await checkMember(chatId, postid)
}
}
}
catch (e) {
// a big try catch to prevent pending :D
}
}
return new Response("", { status: 200 });
} else {
return new Response("wrong webhook", { status: 200 });
}
}
return new Response("ok", { status: 200 });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment