我想用python为电报机器人编写一个计时器。bot得到了";时间“;来自用户';s msg(str)。我怎样才能转换;时间“;从msg到(int)类型?
我编写了这段代码,需要从用户的消息(字符串类型)中获取“本地时间”。 但我需要这个整数来设置计时器。 “local_time=int(msg.from_user.id,msg.text)”中存在TypeError。 我怎样才能修好它我想用python为电报机器人编写一个计时器。bot得到了";时间“;来自用户';s msg(str)。我怎样才能转换;时间“;从msg到(int)类型?,python,types,timer,message,telegram-bot,Python,Types,Timer,Message,Telegram Bot,我编写了这段代码,需要从用户的消息(字符串类型)中获取“本地时间”。 但我需要这个整数来设置计时器。 “local_time=int(msg.from_user.id,msg.text)”中存在TypeError。 我怎样才能修好它 from aiogram import Bot, types from aiogram.dispatcher import Dispatcher from aiogram.utils import executor import time from Config
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
import time
from Config import TOKEN
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await message.reply("Hi!")
@dp.message_handler(commands=['help'])
async def process_help_command(message: types.Message):
await message.reply("/timer - set timer")
@dp.message_handler(commands=['timer'])
async def set_timer(msg: types.Message):
await bot.send_message(msg.from_user.id, text='How many minutes?')
time.sleep(5)
local_time = int(msg.from_user.id, msg.text)
local_time_b = int(local_time * 60)
await bot.send_message(msg.from_user.id, text='Timer set')
time.sleep(local_time_b)
await bot.send_message(msg.from_user.id, text='The timer has worked')
print("Hello")
if __name__ == '__main__':
executor.start_polling(dp)
local_time=int(msg.from_user.id,msg.text)
TypeError:“str”对象不能解释为整数int函数要求文本作为第一个参数,第二个(可选)是基(如果您使用Python解释具有不同基的字符串,则需要此参数-即二进制) msg.text是用户输入(必须是一个数字),它被强制转换为int
如果您通过命令处理程序处理输入,则需要考虑文本消息包括命令IE代码> /开始12 。 一个选项是删除该命令并获得以下值
首先 停止在异步函数中使用time.sleep()
。
改用等待asyncio.sleep()
第二
学习python的基础知识
第三
@dp.message\u处理程序(命令=['timer'])
异步def计时器\u处理程序(消息:消息):
#从消息中获取参数(它是'str'类型!)
timer\u string=message.get\u args()
#让我们试着把它转换成int`
尝试:
计时器=int(计时器字符串)
除了(ValueError、TypeError):
返回等待消息。回答(“请为计时器设置一个数字。例如:/timer 5”)
#成功!计时器设置好了!
等待消息。应答(为{Timer}'设置的f'Timer)
#睡觉(这样,而不是阻塞'time.sleep')
等待异步睡眠(计时器)
#是时候发送消息了
等待消息。回答(“时间到了!”)
旁白:有人,请添加
aigram
tag不起作用。local_time=int(msg.text)ValueError:以10为基数的int()的文本无效:“/timer”用户键入什么?它必须是一个有效的数字(代码试图将其转换为int以设置计时器),我是用户。我写了一个整数(“1”,例如),然后得到ValueError。我该怎么办?你试着用数字捕捉任何异常。如果出现异常,您可以询问,请输入一个有效的数字。编译器需要一个数字来设置计时器。我发送了这个数字,但编译器认为这是字符串。如何将字符串(“1”)转换为整数(1)?这是我的问题。
local_time = int(msg.text)
# remove '/start'
interval = msg.text[7:]
local_time = int(interval)
print(local_time)