Why can't I send messages to Telegram bot? - python

I'm using Telebot to build a simple Telegram bot. I've set up a message handler that responds to commands succesfully, but when I try to send a single message I get an error if I use the chat id (ex: 1234567890):
Error code: 403. Description: Forbidden: bot can't send messages to
bots
I get a different error when I use the user id (ex: #my_user):
Error code: 400. Description: Bad Request: chat not found
This is my code, the auth is correct:
tg_bot = telebot.TeleBot(TG_TOKEN, parse_mode='MARKDOWN')
tg_bot.send_message(chat_id=CHAT_ID_USER, text="hola test")
Is the bot's chat different to the chat I'm supposed to talk with? Any solution and details about the bot functionality will be apreciated, I'm still learning about that!

try this
import telebot
bot = telebot.TeleBot(token)
#bot.message_handler(commands=['start'])
def start(message):
bot.send_message("1395609507","Hello")
bot.infinity_polling()

If the user under this id has not started your bot, then the bot will not be able to write to him/her first. And in this case it is natural to get the error "chat not found". This error can also be observed when working with users who first used the bot and then blocked it.

Related

How can i force the Telegram Bot to write to the user first (aiogram)?

I'm trying to send welcome message to newcomers to the channel via the bot using Aiogram. However, my bot can't find the chat with the user if he has not started a conversation with the bot before. Are there any solutions of this problem?
I have already managed to handle newcomers and add ids to the db, but
`
#router.chat_member(ChatMemberUpdatedFilter(member_status_changed=(KICKED | LEFT | RESTRICTED)
>>
(ADMINISTRATOR | CREATOR | MEMBER)))
async def on_user_join(event: ChatMemberUpdated):
with grpc.insecure_channel('') as channel:
stub = sub_unsub_pb2_grpc.SubscribtionServiceStub(channel)
timestamp = timestamp_pb2.Timestamp()
timestamp.FromDatetime(datetime.now(tz=timezone.utc))
request = sub_unsub_pb2.SubUnsubEvent(
id=str(event.new_chat_member.user.id),
channelId=str(event.chat.id),
time=timestamp,
subStatus='join'
)
response = sub_unsub_pb2.EventResponse()
stub.TriggerEvent(request)
`
But when I try to send a message, the error chat not found is thrown.
`
await support_bot.send_message(
user_id,
f'Welcome to the channel!'
)
`
Solutions to this problem:
Is to have the bot transfer a message to the user as soon as their ID
is added to the database. This way, the user will have started a
discussion with the bot, and the bot will be capable of finding the
chat when you try to send the welcome message.
Is to use the start command, so that new users can initiate the
discussion with the bot by sending /start command. Also, in the
start command handler, you can check whether the user is a new member
and send a welcome message.
Check the user's presence in the channel by using the
get_chat_member method of the bot, which returns a ChatMember
object. If the status attribute of this object
isChatMember.CHAT_MEMBER_STATUS_LEFT, then the user isn't a member
of the channel anymore and you shouldn't send the message.
Use the message event to listen for all messages transferred by the
user in the channel and check if the user is new or not and send the
welcome message accordingly

Not able to send pictures to telegram

I have a simple telegram code to send text and image.
import telegram
bot = telegram.Bot('********:*********')
bot.sendMessage(chat_id=chat_id, text='hello')
bot.sendPhoto(chat_id=chat_id, photo = 'C:\\Users\\user\\Pictures\\Wallpapers\\alley-89197_1920.jpg')
For a while i was able to atleast send the text but now I am getting the following error:
Unauthorized: Forbidden: bot can't send messages to bots
Could you please advise why I am getting this error?
Please read the official FAQ: https://core.telegram.org/bots/faq#why-doesn-39t-my-bot-see-messages-from-other-bots
TL;DR: Telegram bots can't talk to other Telegram bots.

How to get an old message ID with python telegram bot?

I have a Telegram channel with a bot inside it, which I use to send messages to the channel and edit them with this Python code
import telegram
bot = telegram.Bot(token=MY_TOKEN)
msg = bot.send_message(chat_id=MY_CHANNEL_ID, text="...") # send a message
msg = msg.edit_text("...") # edit the previous message
Sometimes the python bot crashes/closes for whatever reason, when I start the bot again how to recover the ID of a message sent during the previous session so that I'd be able to edit the message again?
I read about this method
bot.edit_message_text(text, chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id)
I guess that for chat_id I have to use MY_CHANNEL_ID but what I don't understand is how to get the message_id of the old message
MANUAL SOLUTION
I found out that the message_id is just the number contained in the post link, so a workaround is to manually copy the post link of a message from the telegram client, for example if the post link is https://t.me/my_channel_name/207 then the message_id is 207 and to edit that message we have to run
bot.edit_message_text(text="...", chat_id=MY_CHANNEL_ID, message_id=207)

How can I get the message content from a (gitlab notification) webhook when using discord.py?

This question has been asked before (How to get the message content printed out of a discord webook! in python) but has been closed. So I hope I'm within my rights to open a new question on the topic?
The following szenario:
We use the discord notification service from gitlab (https://docs.gitlab.com/ee/user/project/integrations/discord_notifications.html) to post new issue/push to master-notifications to one of our discord channels using discord.py. This channel is also linked to another chat via bot so that both chats always have the same content. This is working so far.
When I now try to get print(message.content) it's empty concerning messages from gitlab, even though it displays a message in discord. The basic structure looks like this:
import discord
import re
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
async def on_message(self, message):
# modifying and preparing messages for sync with second chat
# I removed this because it shouldn't have anything to do with the problem
# trying to find the message content
print(message.author)
print(message.content)
print(message)
print('----------')
# write messages into database
client = MyClient()
client.run('TOKEN')
print(message) returns something like <Message id=1234 channel=<TextChannel id=5678 name='some-name' position=1 nsfw=False news=False category_id=9012> type=<MessageType.default: 0> author=<User id=3456 name='Bot Name' discriminator='0000' bot=True> flags=<MessageFlags value=0>>
I did read large parts of the API reference (https://discordpy.readthedocs.io/en/latest/api.html) but could not find anything. Though I could not make heads or tails of the webhook part (https://discordpy.readthedocs.io/en/latest/api.html#webhook-support).
Any ideas how to obtain the message content from a message that comes from a webhook? It's gotta be somewhere ...
Thank you in advance,
Christian
Update 2020-10-23
I have tried getting more details about the information send from GitLab to Discord by creating an event listener via https://pipedream.com/ but it did not record any events (set to "new issue", created several), while a listener for discord (on new messages) worked fine.
The setup is as follows:
Create a Webhook in Discord (https://discord.com/api/webhooks/[id]/[token])
Feed said Webhook into the settings in GitLab and choose from a multitude of triggers.
I do not know how I could get the header-data GitLab sends to Discord under these circumstances. I also checked the Webhook provided by Discord using Postman - it merely returns the Bots basic stats.
GitLab sends the message content as embed (https://discordpy.readthedocs.io/en/latest/api.html#embed)
In my case the information I was looking for was right before my eyes. You can access it, using message.embeds[0].description.
I could not make heads or tails off the API description to embeds, but it seems, I also never tested what it does and then started to go in circles.

send direct message to slack user from a app bot but not in app channel

Is there a way to send direct message to from a bot(myapp/user) to a user say xyz or to a user's slackbot. The message needs to appear against the user and not on the mybot app.
I am using the python slack-client.
Using below code to send the message:
user_id="<touser>"
im_channel=self.open_dm(user_id)
slack_client.api_call("chat.postMessage",channel=im_channel,text="hi buddy", as_user=True)
The above code posts the message in the myapp app channel. Is there a way for the bot to send the message directly to the user and not in the app channel?
OR
Is there a way for the myapp bot to send to slackbot channel addressing the user?
Yes.
Just send a message with the user ID for channel and it will appear in the slackbot channel of that user.
Something like this:
user_id="<touser>"
slack_client.api_call("chat.postMessage",channel=user_id,text="hi buddy")
However, note that every message on Slack must to use a channel that includes so called "direct messages". That is how Slack works.

Categories

Resources