Исходник Чат-Бот для Telegram | Игровой Бот

абоба777

Новичок
Автор темы
9
1
Приветствую! сегодня я поделюсь кодом с разработки простого бота на тему: Камень, Ножницы, Бумага
Данный код вы можете сами изменить, что-то добавить что то убрать - на ваш выбор!

Библиотека: python-telegram-bot (как установить можете найти в инете)
Бот сделан строго для Телеграма!

Код ниже:

Не забудь заменить `YOUR_TELEGRAM_BOT_TOKEN` на токен своего бота, который можно получить у @BotFather в Telegram.

Код чпек:
python
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import random

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Привет! Давай сыграем в Камень, ножницы, бумага. Введи /play чтобы начать игру.")

def play(update, context):
    choices = ["камень", "ножницы", "бумага"]
    user_choice = context.args[0].lower()
    bot_choice = random.choice(choices)

    if user_choice not in choices:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Неверный выбор. Попробуй еще раз.")
        return

    if user_choice == bot_choice:
        result = "Ничья!"
    elif (user_choice == "камень" and bot_choice == "ножницы") or (user_choice == "ножницы" and bot_choice == "бумага") or (user_choice == "бумага" and bot_choice == "камень"):
        result = "Ты победил!"
    else:
        result = "Ты проиграл!"

    context.bot.send_message(chat_id=update.effective_chat.id, text=f"Твой выбор: {user_choice}\nВыбор бота: {bot_choice}\n{result}")

def main():
    updater = Updater(token="YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
    dispatcher = updater.dispatcher

    start_handler = CommandHandler("start", start)
    play_handler = CommandHandler("play", play)

    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(play_handler)

    updater.start_polling()

if __name__ == '__main__':
    main()
 

Dickson

Активный
277
63
удали свой код





test.py:
import telebot
from telebot import types
import random

bot_token = 'token'
bot = telebot.TeleBot(bot_token)

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.InlineKeyboardMarkup()
    rock_button = types.InlineKeyboardButton("🪨", callback_data='rock')
    scissors_button = types.InlineKeyboardButton("✂️", callback_data='scissors')
    paper_button = types.InlineKeyboardButton("📄", callback_data='paper')
    markup.add(rock_button, scissors_button, paper_button)
    bot.send_message(message.chat.id, "Выберите свой вариант:", reply_markup=markup)

@bot.callback_query_handler(func=lambda call: True)
def handle_callback(call):
    user_choice = call.data
    bot_choice = random.choice(['rock', 'scissors', 'paper'])
    result = determine_winner(user_choice, bot_choice)
    bot.send_message(call.message.chat.id, f"Вы выбрали: {get_emoji(user_choice)}\nБот выбрал: {get_emoji(bot_choice)}\n\n{result}\n\nПопробуйте снова!")

    markup = types.InlineKeyboardMarkup()
    rock_button = types.InlineKeyboardButton("🪨", callback_data='rock')
    scissors_button = types.InlineKeyboardButton("✂️", callback_data='scissors')
    paper_button = types.InlineKeyboardButton("📄", callback_data='paper')
    markup.add(rock_button, scissors_button, paper_button)
    bot.send_message(call.message.chat.id, "Выберите свой вариант:", reply_markup=markup)

def determine_winner(user_choice, bot_choice):
    if user_choice == bot_choice:
        return "Ничья!"
    elif (user_choice == 'rock' and bot_choice == 'scissors') or (user_choice == 'scissors' and bot_choice == 'paper') or (user_choice == 'paper' and bot_choice == 'rock'):
        return "Вы победили!"
    else:
        return "Вы проиграли!"

def get_emoji(choice):
    if choice == 'rock':
        return "🪨"
    elif choice == 'scissors':
        return "✂️"
    elif choice == 'paper':
        return "📄"

bot.polling()
 
  • Bug
Реакции: Gloryy и TastyBread123