ModuleNotFoundError

Hi Folks,
I’m making Telegram Bot,but error is coming while running the bot.py file.

My File structure is like:
telegram_bot directory
/telegram_bot(project)
/subscriptions(app)
/tbot(app)
other filers (like .gitignore,.env etc)

I’m sharing code of installed apps in settings.py in telegram_bot project:

# Application definition

INSTALLED_APPS = [
    'tbot',
    'subscriptions',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

the models.py file in subscriptions app:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Subscription(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    subscribed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f'{self.user.username} - {self.subscribed}'

class AdminSettings(models.Model):
    telegram_bot_token = models.CharField(max_length=255)
    telegram_bot_chat_id = models.CharField(max_length=255)

    def __str__(self):
        return f"Telegram Bot Settings"

admin.py of same app:

from django.contrib import admin

from .models import Subscription, AdminSettings

# Register your models here.

admin.site.register(Subscription)

admin.site.register(AdminSettings)

bot.py code in tbot app:

import telebot
from django.conf import settings
from subscriptions.models import Subscription
from .env import BOT_TOKEN

bot = telebot.TeleBot(BOT_TOKEN)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    chat_id = message.chat.id
    bot.reply_to(message, "Welcome to our iPhone price update bot! To subscribe for daily updates, send /subscribe.")

@bot.message_handler(commands=['subscribe'])
def subscribe_user(message):
    chat_id = message.chat.id
    try:
        Subscription.objects.get_or_create(user_id=chat_id)
        bot.reply_to(message, "You have successfully subscribed for daily updates!")
    except:
        bot.reply_to(message, "Something went wrong. Please try again later.")

@bot.message_handler(commands=['unsubscribe'])
def unsubscribe_user(message):
    chat_id = message.chat.id
    try:
        Subscription.objects.filter(user_id=chat_id).delete()
        bot.reply_to(message, "You have successfully unsubscribed from daily updates.")
    except:
        bot.reply_to(message, "Something went wrong. Please try again later.")

if __name__ == '__main__':
    bot.polling()

The problem is that I’m running : python -m bot.py

Error coming:
Traceback (most recent call last):
File “/usr/lib/python3.10/runpy.py”, line 187, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File “/usr/lib/python3.10/runpy.py”, line 110, in _get_module_details
import(pkg_name)
File “/home/kapil/Documents/Programming/Projects/telegram_bot/tbot/bot.py”, line 3, in
from subscriptions.models import Subscription
ModuleNotFoundError: No module named ‘subscriptions’

I don’t know where is the error,help me please.

I have done with the commands like:

   python manage.py makemigrations
    python manage.py migrate

No error coming in that command,server running successfully

Correct. You cannot run Django code that way.

If you want to run code using the Django environment (such as using Django models), the easiest way is to create a custom Django management command.

django server is running correctly and admin is also running perfect.
I want to run bot.py file to test telegram bot.
command I am using :

python bot.py

Why the error is coming I don’t know,I have written the app name in installed_apps.

The error is because you’re trying to use a Django model without properly creating the Django environment within your script. That’s why you want to create the custom management command.

What you have for bot.py will not work the way you’re trying to do it.

I dont understand by custom management command,In other project I have one file name virutalsensor.py I have ran it using python virtualsensor.py.
that is running perfectly.

I’m running it in django environment.

Read the docs referenced above.

Are you using Django models in that script? If so, please post the script here.

Code of bot.py:

import telebot
from django.conf import settings
from subscriptions.models import Subscription
from .env import BOT_TOKEN

bot = telebot.TeleBot(BOT_TOKEN)

@bot.message_handler(commands=['start'])
def send_welcome(message):
    chat_id = message.chat.id
    bot.reply_to(message, "Welcome to our iPhone price update bot! To subscribe for daily updates, send /subscribe.")

@bot.message_handler(commands=['subscribe'])
def subscribe_user(message):
    chat_id = message.chat.id
    try:
        Subscription.objects.get_or_create(user_id=chat_id)
        bot.reply_to(message, "You have successfully subscribed for daily updates!")
    except:
        bot.reply_to(message, "Something went wrong. Please try again later.")

@bot.message_handler(commands=['unsubscribe'])
def unsubscribe_user(message):
    chat_id = message.chat.id
    try:
        Subscription.objects.filter(user_id=chat_id).delete()
        bot.reply_to(message, "You have successfully unsubscribed from daily updates.")
    except:
        bot.reply_to(message, "Something went wrong. Please try again later.")

if __name__ == '__main__':
    bot.polling()

Why the python not able to get the module.

I’ve already answered that question above. Not only that, but I’ve also addressed what you need to do to fix it.