【问题标题】:This code for Telegram bot suposse to work because I copyed it, but does notTelegram bot 的这段代码应该可以工作,因为我复制了它,但没有
【发布时间】:2020-05-16 10:37:14
【问题描述】:

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

我该怎么办?

【问题讨论】:

    标签: python python-3.x bots telegram telegram-bot


    【解决方案1】:

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

    import os
    import telebot
    # Your code...
    

    【讨论】:

    • 谢谢,但是为什么我先导入telebot就不行了?
    • 其实如果你写import telebot import os就可以了。重要的是在使用它之前导入 os 包。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-02
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2021-02-25
      • 2022-12-06
      相关资源
      最近更新 更多