首页 > 解决方案 > Telegram bot 的此代码可以工作,因为我复制了它,但没有

问题描述

我开始学习使用 Python 3 在 Telegram 中制作机器人。我是通过这门课程学习的https://groosha.gitbook.io/telegram-bot-lessons/。在第 2 课中有一个代码

    import telebot

    bot = telebot.TeleBot(config.token)

    @bot.message_handler(commands=['test'])
    def find_file_ids(message):
        for file in os.listdir('music/'):
            if file.split('.')[-1] == 'ogg':
                f = open('music/'+file, 'rb')
                msg = bot.send_voice(message.chat.id, f, None)
                bot.send_message(message.chat.id, msg.voice.file_id, reply_to_message_id=msg.message_id)
            time.sleep(3)


    if __name__ == '__main__':
        bot.polling(none_stop=True)

它必须像这样工作:我将一些音频文件放在音乐文件夹中,然后机器人将音频 ID 发送给我。但是当我复制这段代码时,我每次都会遇到同样的错误:

2020-01-30 19:16:09,945 (util.py:66 WorkerThread2) ERROR - TeleBot: "NameError occurred, args=("name 'os' is not defined",)
Traceback (most recent call last):
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 60, in run
    task(*args, **kwargs)
  File "N2.py", line 7, in find_file_ids
    for file in os.listdir('music/'):
NameError: name 'os' is not defined
"
Traceback (most recent call last):
  File "N2.py", line 17, in <module>
    bot.polling(none_stop=True)
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\__init__.py", line 392, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\__init__.py", line 416, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 109, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\six.py", line 703, in reraise
    raise value
  File "C:\Users\Sergej\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telebot\util.py", line 60, in run
    task(*args, **kwargs)
  File "N2.py", line 7, in find_file_ids
    for file in os.listdir('music/'):
NameError: name 'os' is not defined

我应该做些什么?

标签: pythonpython-3.xbotstelegramtelegram-bot

解决方案


正如解释器所说,您正在使用os模块的功能而不导入它。您必须在代码顶部导入它,例如

import os
import telebot
# Your code...

推荐阅读