Home>
Hello everyone. I'm new to Python, so if any functions are not done quite rationally, then don't swear, I'm specifically interested in my question. I have been studying Python for a week, I decided to write a bot that will have functions:
- Check the weather in your city
- Random number
- Currency rate (I have not started this function yet)
- Game 21 points.
Вот как раз с четвертым пунктом у меня возникло множество проблем. В интернете на каком то сайте нашел, как написать эту игру и решил перенести это в своего бота. Оформил ответы через обычные и inline кнопки и теперь не могу решить такую проблему. Сначала мы спрашиваем игрока о том, будет ли он играть в очко, если ответ да, то мы даем ему карту и спрашиваем с помощью инлайн кнопки, будет ли он брать еще. В этом и проблема, что переменная count и присваевание этой переменной рандомного числа находятся в одной функции, а обработка самого ответа( нажатия на кнопку) в другой. Поэтому я не могу понять, что нужно написать в</li>
if call.data== "yooo":
что тут писать?
for everything to work. Thank you very much in advance
from email import message
import telebot
import random
import pyowm
from site import check_enableusersite
from pyowm.utils.config import get_default_config
from pyowm.commons.exceptions import NotFoundError
from telebot import types
from pyowm import OWM
config_dict= get_default_config()
config_dict['language']= 'ru'
count= 0
owm= OWM('f178d0060acd8023761538095adfcc54', config_dict)
mgr= owm.weather_manager()
bot= telebot.TeleBot("")
@bot.message_handler(commands=['start'])
def welcome(message):
markup= types.ReplyKeyboardMarkup(resize_keyboard= True)
item1= types.KeyboardButton("???? Погода")
item2= types.KeyboardButton("???? Рандомное число")
item3= types.KeyboardButton("???? Курс валют")
item4= types.KeyboardButton("♠️ 21 очко")
markup.add(item1,item2,item3,item4)
bot.send_message(message.chat.id, "Привет, " + message.chat.first_name,reply_markup=markup)
bot.send_message(message.chat.id, "Выбери действие: ")
@bot.message_handler(content_types=['text'])
def lalala(message):
if message.chat.type== "private":
if message.text== "???? Погода":
a= bot.send_message(message.chat.id, "Чтобы узнать погоду, напиши название города.\n Например: Москва")
bot.register_next_step_handler(a, pogodka)
elif message.text== "???? Рандомное число":
bot.send_message(message.chat.id,"Ваше случайное число: " + str(random.randint(0,100)))
elif message.text== "???? Курс валют":
bot.send_message(message.chat.id,"В разработке")
elif message.text=="♠️ 21 очко":
markup1= types.InlineKeyboardMarkup()
item5= types.InlineKeyboardButton("Да",callback_data="yes")
item6= types.InlineKeyboardButton("Нет",callback_data="no")
markup1.add(item5, item6)
bot.send_message(message.chat.id, text='Поиграем в очко?', reply_markup=markup1)
else:
bot.send_message(message.chat.id, "Ошибка. Попробуйте еще раз!")
def pogodka(message):
try:
observation= mgr.weather_at_place(message.text)
w= observation.weather
temp= w.temperature('celsius')["temp"]
#if mgr.weather_at_place(message.text)== None:
#answer= "Ошибка"
answer= "В городе " + message.text + " сейчас "+ w.detailed_status + "\n"
answer += "Температура в данный момент "+str(temp) + "\n"
if temp < -10:
answer += "Значительный морозец. Олежка Хабаров советует тебе вытащить все из камода\nИ надеть на себя"
##elif temp += 0:
##answer += "Ноль градусов. Олежка Хабаров советует надеть что-то более теплое "
elif temp < -1:
answer += "Не так уж и холодно, но оденься лучше потеплее."
elif temp < 10:
answer += "Температура самое то, чтоб заболеть. Поэтому одевайся теплее"
elif temp < 15:
answer += "Почти лето, но прохладно\nЛучше возьми с собой кофту"
elif temp > 16:
answer += "Ну там и жара, везет же людям)"
bot.send_message(message.chat.id, answer)
except NotFoundError:
bot.send_message(message.chat.id,"Такого города не существует!")
@bot.callback_query_handler(func= lambda c: c.data== "yes" or c.data== "no")
def callback_inline(call2):
if call2.message:
count= 0
if call2.data== "yes":
koloda= [6,7,8,9,10,2,3,4,11] * 4
random.shuffle(koloda)
current= koloda.pop()
count += current
bot.send_message(call2.message.chat.id,"Вам попалась карта достоинством %d" %current)
bot.send_message(call2.message.chat.id,"У вас %d очков" %count)
markup2= types.InlineKeyboardMarkup()
item7= types.InlineKeyboardButton("Да",callback_data="yooo")
item8= types.InlineKeyboardButton("Нет",callback_data="nooo")
markup2.add(item7,item8)
abc= bot.send_message(call2.message.chat.id,"Будете брать еще?",reply_markup=markup2)
elif call2.data== "no":
bot.edit_message_text(chat_id=call2.message.chat.id, message_id=call2.message.message_id, text= "Жаль????")
@bot.callback_query_handler(func= lambda c: c.data== "yooo" or c.data== "nooo")
def callback_inlin(call):
if call.message:
#count= 0
if call.data== "yooo":
pass
elif call.data== "nooo":
bot.send_message(call.message.chat.id,"У вас %d очков и вы закончили игру" %count)
bot.polling(none_stop=True)
-
Answer # 1
-
Answer # 2
As far as I can tell, in the indicated place you need to continue the game mechanics -draw the next card to the player. I didn’t deal with bots in the telegram, I don’t quite understand how everything interacts there, but if I were you, I would put the whole game into a separate function, just like you did in the "weather" section.
Related questions
- TypeError: 'list' object is not callable. Literally today I started learning Python and telebot API and I don’t understand what
- python : Asynchronous loop while True
- python : Issue with sqlite3 data output
- python : make sure that the buttons are not detected
- how to remove punctuation marks python3
- python : How to create a window in the game for example (dota2)
- Can't uninstall/install Python
- python : Why does list.remove() incorrectly remove elements in a loop?
- Loading bar in Python 3.x
- python : How to send a single message in response to the user via bot.send_message
In order for "everything to work", you first need to learn Python, and then program bots. And then you will understand that in Python there are a lot of options for solving your problem -from global variablesto calling functions and passing parameters to it. And for one thing -and questions like "I copied the script here, how to add a comma to it" will not arise.