Telegram 机器人的这段代码应该可以工作,因为我复制了它,但没有

This code for Telegram bot suposse to work because I copyed it, but does not

我开始学习用 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

我该怎么办?

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

import os
import telebot
# Your code...

您在代码顶部缺少 import os 语句。 继续学习!