프로그램 사용/ai 프로그램

telegram bot api 로 기능 변경하기

구차니 2026. 5. 25. 23:12

그래서.. openclaw 에서 대화창 인증하고 나서 바로 메뉴가 추가되었던 건가..

그리고 set_my_commands() 로 등록되어도 채팅 내용으로 받아와지진 않는다.

다른 무슨 처리가 별도로 필요한 듯.

 

Bot settings

set_my_commands() Used for setting the list of commands
delete_my_commands() Used for deleting the list of commands
get_my_commands() Used for obtaining the list of commands
get_my_default_administrator_rights() Used for obtaining the default administrator rights for the bot
set_my_default_administrator_rights() Used for setting the default administrator rights for the bot
get_chat_menu_button() Used for obtaining the menu button of a private chat or the default menu button
set_chat_menu_button() Used for setting the menu button of a private chat or the default menu button
set_my_description() Used for setting the description of the bot
get_my_description() Used for obtaining the description of the bot
set_my_short_description() Used for setting the short description of the bot
get_my_short_description() Used for obtaining the short description of the bot
set_my_name() Used for setting the name of the bot
get_my_name() Used for obtaining the name of the bot
set_my_profile_photo() Used for setting the profile photo of the bot
remove_my_profile_photo() Used for removing the profile photo of the bot

[링크 : https://docs.python-telegram-bot.org/en/stable/telegram.bot.html]

 

봇 토큰으로 채팅내 메뉴 목록 보기

import asyncio
from telegram import Bot

async def check_bot_menu():
    # Replace with your actual Bot Token from @BotFather
    bot_token = "YOUR_BOT_TOKEN_HERE"
    bot = Bot(token=bot_token)
    
    print("Fetching active menu commands...")
    # Retrieves a list of BotCommand objects
    commands = await bot.get_my_commands()
    
    if not commands:
        print("No menu commands found. The menu is empty.")
    else:
        print(f"Found {len(commands)} command(s):")
        for cmd in commands:
            print(f"/{cmd.command} - {cmd.description}")

if __name__ == "__main__":
    asyncio.run(check_bot_menu())

 

봇 토큰으로 채팅내 메뉴 비우기

import asyncio
from telegram import Bot

async def remove_bot_menu():
    # Replace with your actual Bot Token from @BotFather
    bot_token = "YOUR_BOT_TOKEN_HERE"
    bot = Bot(token=bot_token)
    
    print("Removing all menu commands...")
    # Passing no arguments clears the commands globally
    await bot.delete_my_commands()
    print("Success! All menu commands have been removed.")

# Run the async function
if __name__ == "__main__":
    asyncio.run(remove_bot_menu())

 

봇 토큰과 채팅id를 이용해서 즉각적으로 메뉴 변경하기.

set_my_commands 로는 대화창을 나가도 바뀌지 않아서, 특정 채팅 아이디 넣어서야 바뀌게 되었음

import asyncio
from telegram import Bot, BotCommand, BotCommandScopeChat

async def force_update_user_menu():
    # 1. 봇 토큰과 대상 유저의 Chat ID를 입력하세요.
    BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
    USER_CHAT_ID = 123456789  # 숫자로 된 유저의 chat_id 입력
    
    bot = Bot(token=BOT_TOKEN)
    
    # 2. 변경하고 싶은 새로운 메뉴 목록을 정의합니다.
    new_commands = [
        BotCommand(command="home", description="🏠 홈 화면으로"),
        BotCommand(command="mypage", description="👤 내 정보 보기"),
        BotCommand(command="support", description="❓ 고객 센터")
    ]
    
    print(f"User({USER_CHAT_ID})의 메뉴를 즉시 변경합니다...")
    
    # 3. scope를 'BotCommandScopeChat'으로 지정하여 특정 chat_id에 즉시 강제 적용
    await bot.set_my_commands(
        commands=new_commands,
        scope=BotCommandScopeChat(chat_id=USER_CHAT_ID)
    )
    
    print("성공! 해당 유저의 텔레그램 앱 화면에서 메뉴가 즉시 업데이트되었습니다.")

if __name__ == "__main__":
    asyncio.run(force_update_user_menu())

 

요건 아직 테스트 안해봄

from telegram import Update, BotCommand, BotCommandScopeChat
from telegram.ext import Application, CommandHandler, ContextTypes

# 봇 토큰 설정
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"

# 1. /start 명령어가 들어왔을 때 실행될 함수 (여기서 메뉴를 즉시 변경)
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    chat_id = update.effective_chat.id
    
    # 해당 유저의 화면에 보일 새로운 메뉴 정의
    new_menu = [
        BotCommand(command="home", description="🏠 홈 화면으로"),
        BotCommand(command="mypage", description="👤 내 정보 보기")
    ]
    
    # 유저 화면의 메뉴 버튼 즉시 업데이트
    await context.bot.set_my_commands(
        commands=new_menu,
        scope=BotCommandScopeChat(chat_id=chat_id)
    )
    
    await update.message.reply_text(
        "반갑습니다! 메뉴 버튼이 업데이트되었습니다.\n"
        "좌측 하단의 [Menu] 버튼을 누르거나 명령어를 입력해보세요!"
    )

# 2. 메뉴 버튼의 /home 처리를 위한 핸들러 함수
async def home_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("🏠 홈 화면으로 이동했습니다.")

# 3. 메뉴 버튼의 /mypage 처리를 위한 핸들러 함수
async def mypage_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    await update.message.reply_text(f"👤 [{user.first_name}] 님의 마이페이지입니다.")


def main():
    # 애플리케이션 빌드
    application = Application.builder().token(BOT_TOKEN).build()

    # ⭐ [핵심] 메뉴에 추가한 명령어들과 핸들러 함수를 1:1로 매핑해줍니다.
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("home", home_command))       # /home 처리
    application.add_handler(CommandHandler("mypage", mypage_command))   # /mypage 처리

    # 봇 시작 (폴링 방식)
    print("봇이 시작되었습니다. 대화를 시작하세요...")
    application.run_polling()

if __name__ == "__main__":
    main()