南锋

南奔万里空,脱死锋镝余

Setting the Bottom-Left Menu Button on Telegram Bot

When chatting with BotFather, you might notice a menu button at the bottom-left corner with various commands. How is this achieved? Keep reading to find out.

Redirect to a URL

For example, if you’ve created a webpage and want the bottom-left menu button to open this webpage directly, it’s quite simple. Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Bot, api } from "https://deno.land/x/grammy@v1.25.0/mod.ts";

const TOKEN = ''; // Your bot token
const bot = new Bot(TOKEN);

// Set the command
bot.command("start", (ctx) => {
ctx.reply("Welcome to my Telegram bot!");
async function setWebAppMenuButton() {
const response = await bot.api.setChatMenuButton({
menu_button: {
type: "web_app",
text: "Open WebApp", // Button text
web_app: {
url: "https://lengmo714.top" // Replace with your WebApp URL
}
}
});
console.log("Menu button set response:", response);
}

setWebAppMenuButton();
});

bot.start();

Run the code above, and when you open your bot interface, you’ll see that the menu button has changed to Open WebApp. On a mobile device, you’ll notice a window icon next to the button, indicating that it’s correctly set up.
Open WebApp

Setting Commands in the Menu

If you want to set up multiple commands in the menu like BotFather does, you can add various features to your bot. Here’s how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Bot, api } from "https://deno.land/x/grammy@v1.25.0/mod.ts";

const TOKEN = ''; // Your bot token
const bot = new Bot(TOKEN);

bot.command("start", (ctx) => {
ctx.reply("Welcome to my Telegram bot!");
});

bot.api.setMyCommands([
{ command: "one", description: "One" },
{ command: "two", description: "Two" },
{ command: "three", description: "Three" },
// More commands can be added
])
.then(() => {
console.log("Commands set successfully");
})
.catch((err) => {
console.error("Error setting commands", err);
});

// Fetch and display the existing commands
bot.api.getMyCommands()
.then((commands) => {
console.log("Current commands:", commands);
})
.catch((err) => {
console.error("Error fetching commands", err);
});

// Start the bot
bot.start();

Run the code above, and when you open your bot, you’ll see the menu you configured at the bottom left, as shown below:
菜单按钮

Note: Neither of the methods above may take effect immediately due to potential caching.

+