如何使用 Django 项目运行电报机器人?

问题描述 投票:0回答:3

现在,要通过 Django 运行机器人,我首先使用 python manage.py runserver 命令,然后按照链接使用我的机器人启动视图。你能告诉我是否有一种更简单的方法可以在启动 Django 项目时自动启动我的机器人?

django telegram-bot python-telegram-bot
3个回答
2
投票

实际上,您可以使用管理命令来运行您的机器人,例如

python manage.py runbot

所有 Django 上下文,包括数据库和设置,都将可用

管理命令页面参考:

https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html


2
投票

也许有点晚了,但你可以执行以下操作:

在manage.py所在的同一文件夹中创建bot.py文件。

在 bot.py 中确保导入以下内容:

import django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = '{Folder where your settings are}.settings'
django.setup()

为了运行你只需输入 python bot.py


0
投票

更圆滑的方式是使用达芙妮和扭曲的环。

pip install daphne

接下来,将 daphne 插入已安装应用程序的顶部。

INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tg_bot',
    'app',
]

最后,从

daphne.server
导入扭曲循环,并在
apps.py
文件中所需应用程序的就绪函数中运行该应用程序。对我来说,它在我的
tg
应用程序中。

from django.apps import AppConfig
from .bot import application
from telegram.ext import Updater
from daphne.server import twisted_loop


class TgConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'tg'

    def ready(self) -> None:
        twisted_loop.run_until_complete(application.initialize())
        twisted_loop.create_task(application.start())
        twisted_loop.create_task(Updater.start_polling(application.updater))
© www.soinside.com 2019 - 2024. All rights reserved.