skip to Main Content

I started learning making bots in Telegram with Python 3. I was learning it by this course https://groosha.gitbook.io/telegram-bot-lessons/. In a lesson 2 there was a code

    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)

and it must work like: I put some audio files in the music folder, and then the bot sends to me the audio id.
But when I copy this code, I am getting the same error every time:

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:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagestelebotutil.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:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagestelebot__init__.py", line 392, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "C:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagestelebot__init__.py", line 416, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagestelebotutil.py", line 109, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "C:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagessix.py", line 703, in reraise
    raise value
  File "C:UsersSergejAppDataLocalProgramsPythonPython37-32libsite-packagestelebotutil.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

What am I supposed to do?

2

Answers


  1. As the interpreter said, you are using os module’s function without importing it. You have to import it at the top of your code, like

    import os
    import telebot
    # Your code...
    
    Login or Signup to reply.
  2. You’re missing an import os statement at the top of your code.
    Keep learning!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search