Python:电报bot的替代while循环

时间:2019-08-16 14:33:10

标签: python-3.x for-loop while-loop python-telegram-bot

我使用此代码从列表“ my_list”中获取随机行,该列表是在下面用while循环创建的,如果我在与机器人对话的电报中键入/ start,则该行有效。

唯一的问题是我的电脑被卡住了,因为这个无限循环正在占用我的全部内存。而且我不喜欢即使我不调用它也能持续工作的循环。

没有while循环的问题是它只读取一次代码,并且每次在电报中键入/ start时都得到同一行。

我尝试过制作函数之类的东西,如果从电报中调用了“ start”,则将其传递给for循环,但是没有结果,因为这对我来说太高级了。

我希望有人给我解决方案,如果在没有while循环的情况下在电报中键入/ start时,可以从my_list中获取新行:')

import time
import urllib.request as urllib
import json
import html
import random

from telegram.ext import Updater
from telegram.ext import CommandHandler

updater = Updater(token='<token>')
dispatcher = updater.dispatcher

while True:
    my_list = ['\"this is line1\"',
        '\"this is line2\"',
        '\"this is line3\"',
        '\"this is line4\"',
        '\"this is line5\"'
        ]

    my_random = random.choice(my_list)

    def func1():
        return my_random

    def start(bot, update):
        bot.send_message(chat_id=update.message.chat_id, text=func1())

    my_handler = CommandHandler('start', start)

    dispatcher.add_handler(my_handler)

    updater.start_polling()

2 个答案:

答案 0 :(得分:0)

如果您不需要使用while循环,则只需编写如下代码:

import time
import urllib.request as urllib
import json
import html
import random

from telegram.ext import Updater
from telegram.ext import CommandHandler

updater = Updater(token='token')
dispatcher = updater.dispatcher

def func1():
    my_list = ['\"this is line1\"',
        '\"this is line2\"',
        '\"this is line3\"',
        '\"this is line4\"',
        '\"this is line5\"'
        ]

    return random.choice(my_list)

def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=func1())

my_handler = CommandHandler('start', start)

dispatcher.add_handler(my_handler)

updater.start_polling()

答案 1 :(得分:0)

谢谢您,Arian,它有效。我在周末找到了另一个解决方案,方法是删除func1函数,然后在start函数中直接指向my_list:text = random.choice(my_list)。 我还拥有无法迭代的代码,可以从API获取随机文本。我不得不将代码放入start函数中。我也可以针对my_list进行此操作。

这是我最后得到的代码:

import time
import urllib.request as urllib
import json
import html
import random

from telegram.ext import Updater
from telegram.ext import CommandHandler

updater = Updater(token='<token>')
dispatcher = updater.dispatcher 

my_list = ['\"this is line1\"',
'\"this is line2\"',
'\"this is line3\"',
'\"this is line4\"',
'\"this is line5\"'
]

def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=random.choice(my_list))

my_handler = CommandHandler('start', start)

dispatcher.add_handler(my_handler)

updater.start_polling()