leaveChat
Returns: TrueOfficial docs ↗
Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
Parameters
chat_idIntegerStringRequiredUnique identifier for the target chat or username of the target supergroup or channel (in the format
@channelusername). Channel direct messages chats aren't supported; leave the corresponding channel instead.Returns
On success, True is returned.
GramIO Usage
Leave a group by numeric chat ID:
ts
await bot.api.leaveChat({ chat_id: -1001234567890 });Leave a public channel by username:
ts
await bot.api.leaveChat({ chat_id: "@mychannelname" });Leave the current chat from a command handler:
ts
bot.command("leave", async (ctx) => {
await ctx.send("Goodbye! Leaving the chat now.");
await bot.api.leaveChat({ chat_id: ctx.chat.id });
});Self-destruct after completing a task — useful for temporary bots:
ts
async function runOneTimeTask(chatId: number) {
// ... do work ...
await bot.api.leaveChat({ chat_id: chatId });
console.log("Task complete, bot left the chat.");
}Errors
| Code | Error | Cause |
|---|---|---|
| 400 | Bad Request: chat not found | Invalid chat_id or the bot is not a member of the specified chat |
| 400 | Bad Request: User_deactivated | The bot's account has been deactivated |
| 400 | Bad Request: method is not available for private chats | chat_id points to a private user chat — bots cannot "leave" private conversations |
| 403 | Forbidden: bot is not a member of the channel chat | Bot is already not a member of the channel |
| 429 | Too Many Requests: retry after N | Rate limit hit — check retry_after, use auto-retry plugin |
TIP
Use GramIO's auto-retry plugin to handle 429 errors automatically.
Tips & Gotchas
- Channel DM chats are not supported. If a channel has a linked discussion group or a "direct messages" chat, use the channel's
chat_id— not the DM chat's ID. - Leaving is permanent and immediate. Once the bot leaves, it stops receiving updates from that chat. There is no "rejoin" method — the bot must be re-added manually by a user.
@usernameworks for public chats. Thechat_idfield accepts@channelusernamefor public channels and supergroups, so you don't need to store the numeric ID.- No confirmation event. After calling
leaveChat, the bot won't receive amy_chat_memberupdate confirming the departure within the same session — the leave is applied immediately. - Use
banChatMemberto kick users, not bots.leaveChatonly makes your bot leave. To remove other users, use banChatMember.
See Also
- banChatMember — remove another member from a chat
- getChat — retrieve chat info before deciding to leave
- getChatMember — check the bot's current membership status in a chat