django-telegrambot icon indicating copy to clipboard operation
django-telegrambot copied to clipboard

Sending message with bot

Open Katerou22 opened this issue 6 years ago • 4 comments

How to send message with bot without handler in this package?!

something just like this: bot.sendmessage().... bot out of any def!

Katerou22 avatar May 13 '18 17:05 Katerou22

You may just obtain a bot from DjangoTelegramBot.getBot() method. If you have more than one bot in your config, you could select it by token or username with bot_id parameter in the call.

example how use a bot in a views:

from django.http import HttpResponse
from django_telegrambot.apps import DjangoTelegramBot

def sendMessageTo(request, chat_id, msg_text):    
    bot = DjangoTelegramBot.getBot(bot_id="myBot")
    bot.sendMessage(chat_id, text=msg_text)
    response = "Message send to %s."
    return HttpResponse(response % chat_id)

JungDev avatar May 16 '18 10:05 JungDev

I use this part of code in celery periodic task:

        bot = DjangoTelegramBot.getBot('bot_name')
        bot.sendMessage(chat_id, "Hello")

But i see only this error: AttributeError: 'NoneType' object has no attribute 'sendMessage' How to fix?

ChD1 avatar Aug 29 '19 09:08 ChD1

I see this error too: AttributeError: 'NoneType' object has no attribute 'sendMessage'

YazdanRa avatar Jul 07 '20 17:07 YazdanRa

It means that the first line does not return a valid bot object. The required settings (i.e. token) must be defined in djangos settings.py and you have to make sure, that this settings are loaded, when the script is called from something else than django/wsgi. The 'bot_name' string need to be replaced with the bots user name (not display name!), which belongs to the token given in settings.py.

lukruh avatar Jul 13 '20 09:07 lukruh