N
N
Nikita2022-01-14 22:32:45
Python
Nikita, 2022-01-14 22:32:45

Telebot. How to execute commands from another .py file in the main .py file?

There are three files main.py , commands.py , weather.py .
When I import everything from commands.py into main.py , then the commands from commands.py work, but content_types= from main.py does not work . (Individually, all files work, everything will also work if I just I will copy all @bot.message_handler to main.py and put them before content_types= , but I would like to understand this issue) weather.py
this is a bot that I made according to the tutorial, and so far there are absolutely no ideas how to shove it here, especially since it doesn’t work with commands.py .

main.py

import telebot
import sys
from requests import get
from config import TOKEN
from commands import *
bot = telebot.TeleBot(TOKEN);

a = ["привет","здарова","ку"]
b = ["пока", "давай", "ухожу", "вали"]

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() in a:
        bot.send_message(message.chat.id, 'Привет, создатель')
    elif message.text.lower() =='ghbdtn':
         bot.send_message(message.chat.id, 'Тебе тоже привет, раскладку переключи')
    elif message.text.lower() in b:
        bot.send_message(message.chat.id, 'Прощай, создатель ')
        
bot.infinity_polling(


commands.py

import telebot
import sys
from requests import get
from config import TOKEN

bot = telebot.TeleBot(TOKEN);

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Бот запущен!\nИ так, вот что может быть буду уметь:')
    bot.send_message(message.chat.id, 'Выводить расписание\nГоворить какая сейчас погода\nИ ещё какую-нить херню, которую в меня запишут...')

@bot.message_handler(commands=['help'])
def help_message(message):
    bot.send_message(message.chat.id, 'Вот список доступных команд:')
    bot.send_message(message.chat.id, '/start - запуск бота\n/help - вывод информации о командах\n/version - вывод информации о текущей версии и её возможностях\n/test1 - первый тест\n/test2 - второй тест ')

@bot.message_handler(commands=['version'])
def version_message(message):
    bot.send_message(message.chat.id, 'Текущая версия бота 1.0')
    bot.send_message(message.chat.id, 'Что умеет эта версия?\n1.Что-то точно умеет')

@bot.message_handler(commands=['test1'])
def test_first(message):
  bot.send_message(message.chat.id, 'ТЕСТ1')
  bot.send_photo(message.chat.id, get('https://ie.wampi.ru/2021/12/12/kitten0.jpg').content)

@bot.message_handler(commands=['test2'])
def test_second(message):
  bot.send_message(message.chat.id, 'ТЕСТ2')
  bot.send_photo(message.chat.id, photo=open('demo-media\pics\kitten1.jpg', 'rb'))


Here is a test when everything works
test.py

import telebot
import sys
from requests import get
from config import TOKEN
bot = telebot.TeleBot(TOKEN);

a = ["привет","здарова","ку"]
b = ["пока", "давай", "ухожу", "вали"]

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Бот запущен!\nИ так, вот что может быть буду уметь:')
    bot.send_message(message.chat.id, 'Выводить расписание\nГоворить какая сейчас погода\nИ ещё какую-нить херню, которую в меня запишут...')

@bot.message_handler(commands=['help'])
def help_message(message):
    bot.send_message(message.chat.id, 'Вот список доступных команд:')
    bot.send_message(message.chat.id, '/start - запуск бота\n/help - вывод информации о командах\n/version - вывод информации о текущей версии и её возможностях\n/test1 - первый тест\n/test2 - второй тест ')

@bot.message_handler(commands=['version'])
def version_message(message):
    bot.send_message(message.chat.id, 'Текущая версия бота 1.0')
    bot.send_message(message.chat.id, 'Что умеет эта версия?\n1.Что-то точно умеет')

@bot.message_handler(commands=['test1'])
def test_first(message):
  bot.send_message(message.chat.id, 'ТЕСТ1')
  bot.send_photo(message.chat.id, get('https://ie.wampi.ru/2021/12/12/kitten0.jpg').content)

@bot.message_handler(commands=['test2'])
def test_second(message):
  bot.send_message(message.chat.id, 'ТЕСТ2')
  bot.send_photo(message.chat.id, photo=open('demo-media\pics\kitten1.jpg', 'rb'))

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() in a:
        bot.send_message(message.chat.id, 'Привет, создатель')
    elif message.text.lower() =='ghbdtn':
         bot.send_message(message.chat.id, 'Тебе тоже привет, раскладку переключи')
    elif message.text.lower() in b:
        bot.send_message(message.chat.id, 'Прощай, создатель ')
        
bot.infinity_polling()


To weather.py

from pyowm import OWM
from pyowm.utils import config
from pyowm.utils import timestamps
from pyowm.utils.config import get_default_config
import telebot
import math

owm = OWM('5f1d018a2166335030c30ccae2a7a25f')
mgr = owm.weather_manager()

config_dict = get_default_config()
config_dict['language'] = 'ru' 


bot = telebot.TeleBot("5056685003:AAHXVOqOODh8w8oIZpKUGxN0DWN2Kxlxr9Y", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN

@bot.message_handler(content_types=['text'])
def send_echo(message):
  observation = mgr.weather_at_place( message.text )
  w = observation.weather
  temp = w.temperature('celsius')['temp']
  wind = w.wind()['speed']

  answer = "В городе " + message.text +" сейчас " + w.detailed_status + "\n"
  answer += "Температура сейчас в районе " + str(round(temp)) + " градусов по Цельсию" + "\n\n"
  answer += "Скорость ветра " + str(wind) + " м/с " + "\n\n"
  bot.send_message(message.chat.id, answer)


Will it work if I just refer to main.py
@bot.message_handler(content_types=['text'])
def send_echo(message):
  observation = mgr.weather_at_place( message.text )
  w = observation.weather
  temp = w.temperature('celsius')['temp']
  wind = w.wind()['speed']

and display a response message.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question