python - 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
我应该做些什么?
解决方案
正如解释器所说,您正在使用os
模块的功能而不导入它。您必须在代码顶部导入它,例如
import os
import telebot
# Your code...
推荐阅读
- javascript - 如何将单击按钮更改为窗口加载
- excel - 直到单元格值介于 -1 和 1 之间
- javascript - Google Apps 脚本类 UrlFetchApp 用于获取网址不以“http://”开头的网页
- javascript - 按类型单击 selenium 中的项目
- javascript - 无法让凉亭安装聚合物“凉亭组件”文件夹丢失?
- office-js - 有没有办法以编程方式跟踪 word doc 中的更改?
- firebase - 铸造 firebaseId 令牌异常缓慢
- c++ - 如何将 uint8 列表转换为相应的有符号值?
- matlab - 如何使用带有以下名称的名称保存 .mat 文件:
- jquery - 选择和复选框计算器一直给出 NaN,除非两个选择都被勾选