Git Product home page Git Product logo

django-telegrambot's People

Contributors

alistvt avatar autoantwort avatar hosseynjf avatar jungdev avatar leikoilja avatar lukruh avatar peleccom avatar rafis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

django-telegrambot's Issues

Old Handler API is deprecated

When I run my project I get this warning:

INFO 2020-06-23 09:53:39,915 apps Django Telegram Bot <POLLING mode>
/home/laptop/sampleproject/django_telegrambot/apps.py:225: TelegramDeprecationWarning: Old Handler API is deprecated - see https://git.io/fxJuV for details
  updater = Updater(token=token, request_kwargs=proxy, use_context=context)
INFO 2020-06-23 09:53:40,228 telegrambot Loading handlers for telegram bot

I'm using commit 5f07ec5

update readme

The readme should make clear, whats the difference between this fork and the base repository, especially when further features are added. So I think specific Instructions for this fork should be on top and a link to the original repo and it's documentation below would be enough..

Internal handling of bot settings / bot_data

The bot settings are read from projects settings.py and is used to register ptb bot objects in the apps.py. However the way the settings of the bot are handled may be inconsistent. BotData class, plain variables and the settings itself. Find a consistent way to handle the settings and the bots itself. When bots should be created from app settings this has to be changed anyway.

context based handlers by default

ptb changed the default for handlers to context instead of bot, update, kwargs within v13. This should be done similar to django settings, to avoid confusion and get rid of the deprecated handler api.

Specify supported Django versions

I assume we should specify the Django versions that are supported. Also, need to add these to tox.ini

According to Django supported versions policy, it's worth to support 2.2 and 3.0 at that moment.

What do you think about this?

WEBHOOK doesn't work!

Hi,

My project works fine in case I set POLLING while is doesn't work at all with WEBHOOK. I suspect I missed smoothing in settings.py but I couldn't figure it out.

May I get some help please?

NOTES:

  1. I'm still newbie in both django and django-telegrambot so forgive me for the silly questions.
  2. My project root is https://mydomain.com/api/
  3. As you can see I use REST framework which works fine in https://mydomain.com/api/
  4. I couldn't know where can I catch the errors regarding WEBHOOK but Apache always identify error #6 as [wsgi:error]
  5. I successfully generated mydomain-crt.pem using win-acme for Let's Encrypt; It works fine for django in general but I'm not sure about it for django-telegrambot
  6. I'm able to access https://mydomain.com/api/admin/django-telegrambot/ and see:
    image

settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxx'
DEBUG = False # NOTE: Dev mode

ALLOWED_HOSTS = [
    '.mydomain.com',
    '.mydomain.com.',
    '.mydomain.com',
    '.mydomain.com.',
]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_telegrambot',
    'api',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'somebot.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'somebot.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# TODO: Internationalization
LANGUAGE_CODE = 'en'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "static")

DJANGO_TELEGRAMBOT = {
# FIXME: Bot dosn't response in Webhook mode 
    'MODE' : 'WEBHOOK', # (Optional [str]) 
    'WEBHOOK_SITE' : 'https://mydomain.com',
    'WEBHOOK_PREFIX' : '/api/',  
    'WEBHOOK_CERTIFICATE' : 'C:/apache-certs/mydomain-crt.pem', 

    'BOTS' : [
        {
           'TOKEN': '1234567890:xxxxxxxxxxxxxxxxx',
        },
    ],

}

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR, "uploads")

create pypi package

even if I would prefer to contribute to the original package, which seems to be not maintained anymore, it may be useful to distribute a new package, to make installation easier and more obvious where to make PR and raise issues. Maybe we can create something like dj-telegrambot or django-telegrambot-2 and make transparent, that it's just a continuation of the original project. I want to be sure not to hurt any copyrights or license and will try to contact the original maintainer again before doing so.

Webhook does not appear to be set

On start it seems to be setting the webhook URL. However, when sending messages to the bot, nothing gets posted to the webhook and pending updates keeps increasing.

Telegram Bot <BOT_NAME> setting webhook [ https://<URL>/users/telegram-webhook/<BOT_TOKEN>/ ] max connections:40 allowed updates:['ALL'] **pending updates:8** : True

When I manually access the webhook URL I can see that it's working as I get a {} response and I see an entry in the webserver logs. But I don't see anything if I send a message via Telegram and I do not see any line entry in the webserver logs at all as well.

settings.py

DJANGO_TELEGRAMBOT = {

    'MODE' : 'WEBHOOK', #(Optional [str]) # The default value is WEBHOOK,
                        # otherwise you may use 'POLLING'
                        # NB: if use polling you must provide to run
                        # a management command that starts a worker

    'WEBHOOK_SITE' : '<URL>',
    'WEBHOOK_PREFIX' : '/users/telegram-webhook/', # (Optional[str]) # If this value is specified,
                                  # a prefix is added to webhook url

    #'WEBHOOK_CERTIFICATE' : 'cert.pem', # If your site use self-signed
                         #certificate, must be set with location of your public key
                         #certificate.(More info at https://core.telegram.org/bots/self-signed )

    'STRICT_INIT': True, # If set to True, the server will fail to start if some of the
                         # apps contain telegrambot.py files that cannot be successfully
                         # imported.

    'DISABLE_SETUP': False, # If set to True, there will be no tries to set webhook or read
                            # updates from the telegram server on app's start
                            # (useful when developing on local machine; makes django's startup faster)

    'BOT_MODULE_NAME': 'telegrambot', #(Optional [str])  # The default name for file name containing telegram handlers which has to be placed inside your local app(s). Default is 'telegrambot'. Example is to put "telegrambot_handlers.py" file to local app's folder.

    'BOTS' : [
        {
           'ID': 'MainBot', # Unique identifier for your bot (used in your code only)

           'TOKEN': '<BOT_TOKEN>', # Your bots token (provided by botfather)

           'CONTEXT': True,  # Use context based handler functions (should be true for future versions)

           #'ALLOWED_UPDATES':(Optional[list[str]]), # List the types of
                                                   #updates you want your bot to receive. For example, specify
                                                   #``["message", "edited_channel_post", "callback_query"]`` to
                                                   #only receive updates of these types. See ``telegram.Update``
                                                   #for a complete list of available update types.
                                                   #Specify an empty list to receive all updates regardless of type
                                                   #(default). If not specified, the previous setting will be used.
                                                   #Please note that this parameter doesn't affect updates created
                                                   #before the call to the setWebhook, so unwanted updates may be
                                                   #received for a short period of time.

           #'TIMEOUT':(Optional[int|float]), # If this value is specified,
                                   #use it as the read timeout from the server

           #'WEBHOOK_MAX_CONNECTIONS':(Optional[int]), # Maximum allowed number of
                                   #simultaneous HTTPS connections to the webhook for update
                                   #delivery, 1-100. Defaults to 40. Use lower values to limit the
                                   #load on your bot's server, and higher values to increase your
                                   #bot's throughput.

           # 'MESSAGEQUEUE_ENABLED':(Optinal[bool]), # Make this True if you want to use messagequeue

           # 'MESSAGEQUEUE_ALL_BURST_LIMIT':(Optional[int]), # If not provided 29 is the default value

           # 'MESSAGEQUEUE_ALL_TIME_LIMIT_MS':(Optional[int]), # If not provided 1024 is the default value

           # 'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE':(Optional[int]), # If not provided 8 is the default value

           #'POLL_INTERVAL' : (Optional[float]), # Time to wait between polling updates from Telegram in
                           #seconds. Default is 0.0

           #'POLL_CLEAN':(Optional[bool]), # Whether to clean any pending updates on Telegram servers before
                                   #actually starting to poll. Default is False.

           #'POLL_BOOTSTRAP_RETRIES':(Optional[int]), # Whether the bootstrapping phase of the `Updater`
                                   #will retry on failures on the Telegram server.
                                   #|   < 0 - retry indefinitely
                                   #|     0 - no retries (default)
                                   #|   > 0 - retry up to X times

           #'POLL_READ_LATENCY':(Optional[float|int]), # Grace time in seconds for receiving the reply from
                                   #server. Will be added to the `timeout` value and used as the read timeout from
                           #server (Default: 2).
        },
        # Other bots here with same structure.
    ],

}

update url patterns

Django provided some new functionality for url patterns. Even if it's backward compatible, it would be nice to update it some when.
This is what djangos system check told me.

WARNINGS:
?: (urls.W002) Your URL pattern '/(?P<bot_token>.+?)/$' [name='webhook'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.

also update the include in the installation process.

your first django-telegram-bot guide

I'm going to write a short guide with some links and additional information for ppl having never used telegram bots before. I try to stay as close as possible to the first steps guide of python-telegram-bot and make the differences in the code and the role of this library as clear as possible.

Dispatcher initialization problem

If we define dispatcher with dispatcher property, then it works correctly according to the new context approach of ptb 12
dp = DjangoTelegramBot.dispatcher

If we define dispatcher with getDispatcher method, then dispatcher is constructed for old version (not for ptb 12)
dp = DjangoTelegramBot.getDispatcher('my_token')

Error during installation

I did try to install by following command

pip install -e git+https://github.com/telebotter/django-telegrambot.git#egg=django-telegrambot --upgrade

FileNotFoundError: [Errno 2] No such file or directory: 'README.rst'

Is anybody else also facing same error?

run tests

the tests should be updated at least for the new features. I'm not used to write tests, but I will give my best. Maybe it's worth a look to django manage.py test too.

Warning "Asynchronous callbacks can not be processed without at least one worker thread" when runngin commands

We are getting the warning

/venv/lib/python3.7/site-packages/telegram/ext/dispatcher.py:251: UserWarning: Asynchronous callbacks can not be processed without at least one worker thread.
 'Asynchronous callbacks can not be processed without at least one worker thread.'

every time a cron jobs executes a command in production. So we currently getting 1440 cron job mails a day :D

Is there a way to disable this or why we get this error in general, locally I don't get this error?

Can we prevent that all the telegrambot_handlers.py gets loaded when a command gets executed?

Thanks in advance :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.