TBL Codes
306 subscribers
6 photos
2 files
46 links
Download Telegram
Command: *

if (!msg && !msg?.text) return;
if (message && message.match(/[0-9]{8,10}:[a-zA-Z0-9_-]{35}/)) {
let potentialToken = message.match(/[0-9]{8,10}:[a-zA-Z0-9_-]{35}/)[0];


let botCheck = await HTTP.get({
url: "https://api.telegram.org/bot" + potentialToken + "/getme"
})

if (botCheck.ok && botCheck.data.ok) {
Api.deleteMessage({
chat_id: chat.id,
message_id: request.message_id
});
let tag = Libs.tgutil.getUserMention(user, {
parseMode: 'html',
showId: false
});

// Send warning message and tag user
let warningMsg = await Api.sendMessage({
text: `
⚠️ <b>Warning!</b>

${tag}, you just shared a <b>bot token</b>!

πŸ”’ <i>Bot tokens should never be shared publicly.</i>
🚫 Anyone with it can control your bot.

Please <b>revoke this token immediately</b> from <a href="https://t.me/BotFather">@BotFather</a>.

πŸ•’ This message will self-destruct in <b>10 seconds</b>.
`,
parse_mode: "HTML"
});

// Wait 10 seconds and delete warning message
await sleep(10000); //must be awaited and in ms(milliseconds) max 10s = 10000ms
warningMsg.delete();
}
}

Auto detects valid bot tokens in chat and delete those messages to keep everything safe

🌐 FREE Telegram Bot Hosting : telebothost.com
❀5
How to clone bot in TeleBotHost

const res = await TBL.clone({
  bot_id: bot.id,//bot id required
  start_now: true,//if want to clone and start now , optinal
  bot_token: '12345:abc', //start_now needs bot token for which bot need to start , optional
  all_prop: true, //true if want all prop to copy only bot prop supported, optional
  bot_props: {
    theme: 'dark', //prop 1
    welcome: 'Welcome to my new bot!' //prop2
  } //Custom prop to pass , auto type detection , optional
});

Bot.inspect(res)//check the response

/*
{
ok: true,
result: {
bot_id: 544xxxxx,
bot_name: 'Tbl Test',
owner: 'mymail@telebothost.com',
commands_count: 9
}
}
*/

How to tranfer bot in TeleBotHost

const result = await TBL.transfer({
bot_id: bot.id,
to_mail: 'newuser@telebothost.com'
});



Docs : https://telebothost.com/docs/#class-tbl
πŸ’‘ TBL Tip 1:

When using if conditions, always use optional chaining to avoid runtime errors

βœ… Use:

if (update?.message) { ... }

❌ Avoid:

if (update.message) { ... }

This ensures your code won’t break if update is null or undefined.

#tip@TBHCodes
❀4
πŸ’‘ TBL Tip  2

Always wrap code in commands like @, @@ , or * with proper update checks. 
Example in * or @@: 
if(!user || !user?.id) return;
//Early retrun if user is null or user don't have id

But in @
function check(){
if(!user || !user?.id) return;
}
check()

Some updates (like channel updates ) don’t have user objects or just {} and that can cause errors. 
Keep your code update-aware to avoid undefined issues.

Note: in @ command don't use retrun statement directly first made a function and use into that

#tip@TBHCodes
πŸ‘1
Forwarded from TeleBotHost
We have updated few things:

1. updated our Webhook class
2. Added Webapp class
3. Updated res class

Tip: Webhook and Webapp class are just for genarate the URLs, and res is for sending response to client

If any error occurs just fell free to tell us
Forwarded from TeleBotHost
πŸš€ Update: Async Error Handling Fixed!

We’ve just rolled out an important fix for the Bot class async behavior πŸ› οΈ
Now all Bot methods like Bot.run() and Bot.runCommand() will throw errors properly β€” no more silent failures!

Also, message-related methods such as Bot.sendMessage() will now log errors directly in your bot error logs

βœ… More reliable
βœ… Easier debugging
βœ… Cleaner flow

Read more here:
https://telebothost.com/docs/#async-error
Style 1

let progress = 0;

function bar(p) {
const filled = Math.floor(p / 12.5); // 8 total segments
return "β–°".repeat(filled) + "β–±".repeat(8 - filled);
}

const mes = await Api.sendMessage({ text: `${bar(progress)} ${progress}%` });

while (progress < 100) {
const step = Math.floor(Math.random() * 10) + 6; // +6–15%
progress = Math.min(progress + step, 100);
await sleep(80 + Math.random() * 70); // 80–150ms delay
await mes.editText(`${bar(progress)} ${progress}%`);
}

await mes.editText("βœ… Done!");

Style 2

let progress = 0;

function bar(p) {
const filled = Math.floor(p / 12.5); // 8 total segments
return `[${"β–“".repeat(filled)}${"β–‘".repeat(8 - filled)}]`;
}

const mes = await Api.sendMessage({ text: `${bar(progress)} ${progress}%` });

while (progress < 100) {
const step = Math.floor(Math.random() * 10) + 6; // +6–15%
progress = Math.min(progress + step, 100);
await sleep(80 + Math.random() * 70); // 80–150ms delay
await mes.editText(`${bar(progress)} ${progress}%`);
}

await mes.editText("βœ… Done!");

TBL code to make a progress bar
❀108πŸ‘52
Forwarded from BIZ FACTORY (Cyropes -_-)
let api_url = "https://zenquotes.io/api/random";
let response = await HTTP.get(api_url);


if (response.status === 200 && response.data) {
let data = response.data;
let quote = data[0].q;
let author = data[0].a;

// coded by @bizft
let message_text = *❝ ${quote} ❞*\n\nβ€” *${author}*;


msg.reply(message_text, { parse_mode: "Markdown" });
} else {


msg.reply("❌ Failed to fetch a quote. Please try again later.", { parse_mode: "Markdown" });
}

Setup Guide:
1️⃣ Create Your Bot:
Β· Go to telebothost.com and create your bot

2️⃣ Add Command:
Β· Create a new command (you can choose any name like /quote, /inspire, /motivation)
Β· Paste the above code into the command

3️⃣ Deploy & Test:
Β· Deploy your bot
Β· Send your chosen command to get a random quote! βœ…
Example Usage:
Β· /quote - Get random inspirational quote


🧠Made by @bizft
❀2
Forwarded from TeleBotHost
A request to all members

Please don’t just copy code from other platforms and paste it into TBL. It often won’t work that way. We have proper docs and many AI tools to help you learn β€” use them!

If you use GPT or any AI, read the code carefully and understand how it works. If something fails, ask clearly and learn from it.

Don’t be a copy-paster, be a real coder.
πŸ”₯4
Forwarded from TeleBotHost
Interested in contributing to TBL and proving your skills as a real supporter and developer?

Create your own TBL Library and share your creativity with the community.

β€’ Build a unique or useful TBL Lib
β€’ Submit a Pull Request at: https://github.com/telebothost/tbl-libs
β€’ If we like your library, we will definitely add it to the official collection.

Show your best work and help grow the TBL ecosystem.

Tip: Before submitting, always test your library code.

How: Simply paste your library code inside the @ command, comment out the module export section, and test your functions or variables directly using the names you defined β€” not Libs.xx.yy.
Forwarded from xBotsBusiness
🌟 Group Name Changer TBL Code

Command - /change
Example: /change Group Name

TBL Code -
/* Command: /change */

// Step 1: Check if this is a group or supergroup
if (chat.type === "private") {
Bot.sendMessage("This command can only be used in groups.");
return;
}

// Step 2: Check if the user provided a new name in 'params'
let newTitle = params;
if (!newTitle) {
Bot.sendMessage("Please provide a new name.\nUsage: /change <new group name>");
return;
}

// Step 3: Check if the user sending the command is an admin or owner
let userMember = await Api.getChatMember({
chat_id: chat.id,
user_id: user.id
});

// Check if the API call was successful
if (!userMember.ok) {
Bot.sendMessage("Error: Could not verify your permissions.");
return;
}

// Check the user's status
let userStatus = userMember.result.status;
if (userStatus !== "administrator" && userStatus !== "creator") {
Bot.sendMessage("Sorry, only group admins and the owner can use this command.");
return;
}

// Step 4: Check if the bot is an admin and has the right permission
let botMember = await Api.getChatMember({
chat_id: chat.id,
user_id: bot.bot_id // bot.bot_id is the bot's own Telegram ID
});

if (!botMember.ok) {
Bot.sendMessage("Error: Could not verify my own permissions.");
return;
}

// Check if the bot is an admin AND has the 'can_change_info' permission
if (botMember.result.status !== "administrator") {
Bot.sendMessage("I am not an admin in this group. Please promote me first.");
return;
}

if (!botMember.result.can_change_info) {
Bot.sendMessage("I am an admin, but I'm missing the 'Change Group Info' permission.");
return;
}

// Step 5: All checks passed. Attempt to change the group title.
try {
let result = await Api.setChatTitle({
chat_id: chat.id,
title: newTitle
});

if (result.ok) {
// You can send a confirmation message
Bot.sendMessage("βœ… Group title has been changed to: " + newTitle);
} else {
// Send a specific error if Telegram rejects it
Bot.sendMessage("Failed to change title. Telegram error: " + result.description);
}
} catch (e) {
Bot.sendMessage("An unexpected error occurred: " + e.message);
}


Pleatform - telebothost.com
Creadit - https://gemini.google.com/gem/1Ef-plIMo6G6dFOjB2I85CrzCnrqbbcd3?usp=sharing ( TBL Helper Ai )
❀1
Command: /ask
/*Command: /ask
answer: πŸ€” Please ask your question
need_reply: true*/
if(!message) return ;
let question = message.trim()
if (!question || question.length === 0) {
Bot.sendMessage("❌ Please provide a valid question!")
return
}
let tempMsg = await Bot.sendMessage("πŸ€” Thinking...")

try {
let response = await HTTP.get({
url: "https://api-xqwa.onrender.com/chat/completion",
query: {
message: question,
style: "chatgpt-alternative"
}
})

if (response.ok && response.data && response.data.status === 200) {
let aiResponse = response.data.response
Api.editMessageText({
chat_id: chat.id,
message_id: tempMsg.result.message_id,
text: "πŸ’¬ *Your Question:*\n" + question + "\n\n*Answer:*\n" + aiResponse,
parse_mode: "Markdown"
})
} else {
Api.editMessageText({
chat_id: chat.id,
message_id: tempMsg.result.message_id,
text: "⚠️ Sorry, I couldn't process your question. Please try again later.\n\n*Error:* API returned status " + (response.data ? response.data.status : "unknown")
})
}

} catch (error) {
Api.editMessageText({
chat_id: chat.id,
message_id: tempMsg.result.message_id,
text: "❌ An error occurred while processing your request. Please try again.\n\n*Error:* " + (error.message || "Network error")
})
}

Chat AI TBL code by @Death_Walkers
❀1
πŸ’‘TBL Tip 3: When accessing multiple properties, use Promise.all() to run them in parallel β€” it's much faster ⚑️

βœ… Do this (parallel) :

let start = Date.now()
let results = await Promise.all([
Bot.get("user_1"),
Bot.get("user_2"),
Bot.get("user_3"),
Bot.get("user_4"),
Bot.get("user_5")
])
Bot.inspect({
took: Date.now() - start + "ms",
results
})

It will take 1-3ms even 10+ properties

❌ Don’t do this (sequential):
let a =  Bot.get("user_1")
let b = Bot.get("user_2")
let c = Bot.get("user_3")
let d = Bot.get("user_4")
let e = Bot.get("user_5")

That version runs each one after the previous finishes,
making your bot slower ⏳ especially with many keys.
Please open Telegram to view this post
VIEW IN TELEGRAM
πŸ“Œ TTS Generator TBH Code πŸ“Œ

This code is tested & working perfectly βœ…

πŸ“œ Description:
Advanced Text-to-Speech generator that converts text into natural speech audio and supports 10 languages with high-quality voice output also to view more languages & voice accents click here

πŸš€ Command: /tts

⏳ Wait for answer: ❌ Off

πŸ›  TBH Code:

let textToConvert = "";
let languageToUse = "en";
if (params) {
let parts = params.trim().split(" ");
let supportedLanguages = ['en','hi','ur','ta','es','fr','de','it','ru','ja'];
let lastPart = parts[parts.length - 1].toLowerCase();
if (parts.length >= 2 && supportedLanguages.includes(lastPart)) {
textToConvert = parts.slice(0, -1).join(" ");
languageToUse = lastPart;
} else {
textToConvert = params;
}
} else {
Api.sendMessage({
chat_id: chat.id,
text: "❌ Please provide text to convert!\n\n<b>Usage:</b>\nβ€’ /tts <code>{text} {langcode}</code>\nβ€’ /tts <code>{text}</code>\n\n<b>Example:</b>\nβ€’ <code>/tts hello</code>\nβ€’ <code>/tts hello en</code>",
parse_mode: "HTML",
reply_to_message_id: msg.message_id
});
return;
}
if (!textToConvert.trim()) {
Api.sendMessage({
chat_id: chat.id,
text: "❌ No text found to convert!",
parse_mode: "HTML",
reply_to_message_id: msg.message_id
});
return;
}
if (textToConvert.length > 500) {
Api.sendMessage({
chat_id: chat.id,
text: "❌ Text too long. Maximum 500 characters allowed.",
parse_mode: "HTML",
reply_to_message_id: msg.message_id
});
return;}
let statusMsg = await Api.sendMessage({
chat_id: chat.id,
text: "πŸ”„ Processing your TTS request... This may take a few seconds",
parse_mode: "HTML",
reply_to_message_id: msg.message_id});
try {
Api.sendChatAction({
chat_id: chat.id,
action: "upload_audio"
});
let response = await HTTP.post({
url: "https://flashcomapi.alwaysdata.net/api/tts-free",
body: {
text: textToConvert.trim(),
language: languageToUse,
telegram_id: user.id.toString(),
provider: "gs" //You can change to 'vi' read more: https://telegra.ph/Free-TTS-API---Voice-Models-Documentation-11-05
},
headers: {
"Content-Type": "application/json"
}
});
if (response.ok && response.data) {
if (response.data.success === true && response.data.url) {
let providerInfo = {
'gs': 'gs - Best Quality',
'vi': 'vi - Medium Quality',
'cache': 'Cache - Previously Generated'
};
let serviceName = providerInfo[response.data.service_used] || response.data.service_used;
let caption = `<b>🎧 TTS Generation Complete!</b>\n\n<b>πŸ“ Text:</b> ${textToConvert.trim()}\n<b>🌐 Language:</b> ${languageToUse.toUpperCase()}\n<b>πŸ”§ Provider:</b> ${serviceName}\n<b>⏱️ Processing Time:</b> ${response.data.processing_time}ms\n<b>πŸ“¦ File Size:</b> ${(response.data.file_size / 1024).toFixed(2)} KB\n<b>πŸ†” Request ID:</b> <code>${response.data.request_id}</code>\n\n<b>🌟 Available Providers:</b>\nβ€’ <b>gs</b> - Highest Audio Quality β€’ Multiple Languages\nβ€’ <b>vi</b> - Professional Quality β€’ Voice Models\n\n<b>πŸ”— API Docs:</b> <a href="${response.data.docs}">FlashCom API</a>\n<b>πŸ‘₯ Channel:</b> <a href="${response.data.channel}">FlashCom Official</a>\n\n<b>πŸ’‘ Note:</b> <i>${response.data.note}</i>`;
Api.deleteMessage({
chat_id: chat.id,
message_id: statusMsg.result.message_id
});
Api.sendAudio({
chat_id: chat.id,
audio: response.data.url,
parse_mode: 'HTML',
caption: caption,
reply_to_message_id: msg.message_id
});
} else {
let errorMsg = response.data.error || JSON.stringify(response.data);
Api.editMessageText({
chat_id: chat.id,
message_id: statusMsg.result.message_id,
text: `❌ API Error: ${errorMsg}`
});
}} else {
let errorMsg = response.data?.error || response.content || "HTTP request failed";
Api.editMessageText({
chat_id: chat.id,
message_id: statusMsg.result.message_id,
text: `❌ Error: ${errorMsg}`
});
}} catch (error) {
Api.editMessageText({
chat_id: chat.id,
message_id: statusMsg.result.message_id,
text: `❌ Request Failed: ${error.message}`
});
}

//For more lang code and voice accents :
//https://telegra.ph/Free-TTS-API---Voice-Accents--Language-Documentation-11-06

//For more apis:
//https://flashcomapi.alwaysdata.net/

//Note: 'gs' does not support voice accents, only 'vi' supports


β€’ @FlashComAssistant
🌚1
TBL Codes pinned Β«πŸ’‘TBL Tip 3: When accessing multiple properties, use Promise.all() to run them in parallel β€” it's much faster ⚑️ βœ… Do this (parallel) : let start = Date.now() let results = await Promise.all([ Bot.get("user_1"), Bot.get("user_2"), Bot.get("user_3")…»
/*Command: /img
aliases: imghost, host, upload

Usage:
Method 1: /img <image_url>
Method 2: Reply to an image with /img

Example:
/img https://example.com/image.png
or reply to any image with /img
*/

let imageUrl = null
let repliedMsg = null

if (request && request.reply_to_message) {
repliedMsg = request.reply_to_message
} else if (msg && msg.reply_to_message) {
repliedMsg = msg.reply_to_message
}

if (repliedMsg) {
if (repliedMsg.photo && repliedMsg.photo.length > 0) {
let photo = repliedMsg.photo[repliedMsg.photo.length - 1]
let fileId = photo.file_id

try {
let fileInfo = await Api.getFile({ file_id: fileId })

if (fileInfo && fileInfo.ok && fileInfo.result && fileInfo.result.file_path) {
imageUrl = "https://api.telegram.org/file/bot" + bot.token + "/" + fileInfo.result.file_path
} else {
Bot.sendMessage("❌ Failed to get image file path from Telegram")
return
}
} catch (e) {
Bot.sendMessage("❌ Error getting image: " + (e.message || "Unknown error"))
return
}
}

else if (repliedMsg.document) {
let doc = repliedMsg.document
if (doc.mime_type && doc.mime_type.startsWith("image/")) {
let fileId = doc.file_id
try {
let fileInfo = await Api.getFile({ file_id: fileId })

if (fileInfo && fileInfo.ok && fileInfo.result && fileInfo.result.file_path) {
imageUrl = "https://api.telegram.org/file/bot" + bot.token + "/" + fileInfo.result.file_path
} else {
Bot.sendMessage("❌ Failed to get document file path from Telegram")
return
}
} catch (e) {
Bot.sendMessage("❌ Error getting document: " + (e.message || "Unknown error"))
return
}
} else {
Bot.sendMessage("❌ The replied file is not an image")
return
}
} else {
Bot.sendMessage("❌ Please reply to a photo or image file")
return
}
}

if (!imageUrl) {
if (!params || params.trim() === "") {
Bot.sendMessage("❌ No image URL provided\n\nExample:\n/img https://example.com/image.png or reply to image with /img")
return
}

imageUrl = params.trim()

if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
Bot.sendMessage("❌ Invalid URL\n\nPlease provide a valid image URL starting with http:// or https://")
return
}
}

let processingMsg = await Bot.sendMessage("⏳ Uploading your image...\nPlease wait...")

try {
let response = await HTTP.get({
url: "https://image.ashlynn.workers.dev/upload2",
query: { url: imageUrl }
})

if (!response !response.ok response.status !== 200) {
throw new Error("API request failed with status: " + (response ? response.status : "unknown"))
}

let data = response.data

if (!data data.successful !== "success" data.status !== 200) {
throw new Error("Upload failed: " + (data ? JSON.stringify(data) : "No data"))
}

await Api.editMessageText({
chat_id: chat.id,
message_id: processingMsg.result.message_id,
text:
"βœ… Image Hosted Successfully!\n\n" +
"πŸ“· Image ID: " + data.imageId + "\n" +
"πŸ”— Download URL:\n" + data.downloadUrl + "\n\n" +
"πŸ’‘ Click the buttons below to open or Copy",
reply_markup: {
inline_keyboard: [
[
{
text: "🌐 Open Image",
url: data.downloadUrl
}
],
[
{
text: "Copy URL",
copy_text: {"text":data.downloadUrl}
}
]
]
}
})

} catch (error) {
await Api.editMessageText({
chat_id: chat.id,
message_id: processingMsg.result.message_id,
text:
"❌ Failed to upload image\n\n" +
"Possible reasons:\n" +
"β€’ Invalid or inaccessible image URL\n" +
"β€’ Image format not supported\n" +
"β€’ API service is temporarily down\n\n" +
"Error: " + (error.message || "Unknown error") + "\n\n" +
"Please try again with a different image."
})
}


Image uploader TBL Codes by @Death_Walkers
❀1
πŸ’‘ Telegram Tip: Image Cache!

When you send images by URL, Telegram caches them on their CDN.
That means if you update the image on your server, Telegram won’t fetch the new version automatically.

βœ… Fix: Add a random query parameter to the URL:
https://example.com/photo.png?v=12345

This forces Telegram to download the latest version every time.
Forwarded from Krishna ~
Force Channel Join Tbh Code

Command /start

Code:
await Api.sendMessage({
chat_id: chat.id,
text: "*Please join our channel to continue.*\n\n_Join first, then tap β€œI Joined”._",
parse_mode: "Markdown",
reply_markup: {
inline_keyboard: [
[{ text: "Join Channel", url: "https://t.me/Mrnull9" }],
[{ text: "I Joined", callback_data: "check_join" }]
]
}
});


Command check_join

Code:

let channels = ["@Mrnull9"];
let res = await Libs.mcl.check(user.id, channels);

let mid = request.message.message_id;

if (res.all_joined === true) {
Api.editMessageText({
chat_id: chat.id,
message_id: mid,
text: "*Verification Complete!*\n\n_You may continue now._",
parse_mode: "Markdown"
});
} else {
Api.editMessageText({
chat_id: chat.id,
message_id: mid,
text: "*You have not joined yet.*\n\n_Please join first, then tap β€œCheck Again”._",
parse_mode: "Markdown",
reply_markup: {
inline_keyboard: [
[{ text: "Join Channel", url: "https://t.me/Mrnull9" }],
[{ text: "Check Again", callback_data: "check_join" }]
]
}
});
}

Credit & Devloped By: @Raghav768
Telegram Channel:
@MrNull9
❀4πŸ”₯1
Krishna ~
Force Channel Join Tbh Code Command /start Code: await Api.sendMessage({ chat_id: chat.id, text: "*Please join our channel to continue.*\n\n_Join first, then tap β€œI Joined”._", parse_mode: "Markdown", reply_markup: { inline_keyboard: [ …
Little Upgraded version


command: @
const channels = [
  "@Mrnull9"
]


command: /start
const ik = [];

for (const c of channels) {
  ik.push([
    {
      text: "Join to " + c,
      url: "tg://resolve?domain=" + c.slice(1)
    }
  ]);
}

ik.push([
  {
    text: "I Joined",
    callback_data: "check_join"
  }
]);

Api.sendMessage({
  text: "Please join our channel to continue.*\n\n_Join first, then tap β€œI Joined”._",
  reply_markup: {
    inline_keyboard: ik
  }
});


command: check_join
const ik = []; // again???
const res = await Libs.mcl.check(user.id, channels);
const allJoined = res.all_joined;

const text = allJoined
  ? "*Verification Complete!*\n\n_You may continue now._"
  : "*You have not joined yet.*\n\n_Please join first, then tap β€œCheck Again”._";

for (const c of channels) {
  ik.push([
    {
      text: "Join to " + c,
      url: "tg://resolve?domain=" + c.slice(1)
    }
  ]);
}

ik.push([
  {
    text: "Check again",
    callback_data: "check_join"
  }
]);

Api.editMessageText({
  text,
  message_id: request?.message?.message_id,
  parse_mode: "Markdown",
  reply_markup: {
    inline_keyboard: !allJoined ? ik : undefined
  }
});



By : @vinadira
πŸ”₯2❀1
Forwarded from TECH CODER
Example of using emoji effect

Command - /start
Api.sendMessage({
    chat_id: user.telegramid,
    text: "πŸŽ‰ Celebration effect message",
    parse_mode: "Markdown",
    message_effect_id: "5046509860389126442"
});



'πŸ”₯': "5104841245755180586",
'πŸ‘': "5107584321108051014",
'πŸŽ‰': "5046509860389126442",
'πŸ‘Ž': "5104858069142078462",
'❀️': "5044134455711629726",
πŸ”₯6
⭐ TBL Tip: Use Any Telegram API Method Dynamically!

If a method isn’t available in TBL’s Api.xxx, you can still call it:

Api.call("methodName", { /* params */ })

Example:
Api.call("getChat", {
chat_id: -1007657565746
})

Use any new Telegram method instantly πŸš€
Docs: https://telebothost.com/docs/#api-dynamic