Telegram Bot API Python - telegram.error.BadRequest: Chat not found - python

I want to create a bot to post my texts to a channel...
Can anyone help me with the code?
this is the code that I tried :
import telegram
token = "5002307835:AAGOu4f******************"
chat_id = "1382******"
bot = telegram.Bot(token)
def send_message(message):
return bot.send_message(chat_id,message)
send_message("HI")
but i got this error : telegram.error.BadRequest: Chat not found
also i tried : chat_id = "-1382******" and chat_id = -1382****** and chat_id = 1382******

use it without " "
e.g.
import telegram
chat_id = 1382******
token = "TOKEN"
if not work, try it with - and no "", it will works!
e.g.
import telegram
chat_id = -1382******
token = "TOKEN"

Channels ids usually starts with -100, so
chat_id = -1001382******
Put it as integer
You can also get the channel id sending a message in the channel as normal user and handling it with the bot. In message.chat.id you will see the correct id
Or just forward a channel message to the bot https://t.me/nguLikJSONbot

First of all, you should be administrator of a channel and then send message to it.
For send text, file or photo with caption to a specific user, the target user should be member of your bot and then change chat_id to user id in telegram.
import telegram
token = "5002307835:AAGOu4f******************"
# "#{0}".format("botfather") ==> #botfather
chat_id = "#{0}".format("your_channel_name")
# For sending message to a specific user
# chat_id = 18558...
bot = telegram.Bot(token)
def send_message(message):
return bot.send_message(chat_id, message)
your_msg = "Hello"
send_message(your_msg)

Related

Telegram Bot not Connecting to API

I have been using the Telegram API for a while to listen for messages in specific channels on one account. The code below works ok. I tried to use the same code to create another listener for a different account but it doesn't work. I don't get any errors.
When I look on the official Telegram app the listener is not listed under "Devices" which suggests it is not connecting to the API correctly.
Before testing I created a new API ID and hash at my.telegram.org. I've triple checked that the ID, hash and channel ID are all correct.
Can anyone think what the issue might be?
Thanks
from telethon import TelegramClient, events, sync
api_id = 'xxxxxxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxx'
client = TelegramClient('anon', api_id, api_hash)
chat_id = xxxxxxxx
#client.on(events.NewMessage(chats=chat_id))
async def newMessageListener(event):
new_message = event.message.message
chat_id = event.chat_id
print(chat_id)
print(new_message)
print()
screenshot = "new_image.jpg"
if event.message.photo:
await event.download_media(screenshot)
print("New image received")
#client.on(events.NewMessage(chats=[chat_id]))
chats=[] - here must be a python list,
like chats=[-123456789]

How to get the Chat or Group name of Incoming Telegram message using Telethon?

I have this code
from telethon.sync import TelegramClient, events
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage(pattern=pattern))
async def handler(event):
await event.reply("Here should be the Chat or Group name")
How to implement this?
if we are talking only about groups/channels
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = chat_from.title
Else (If we want to get the full name of chat entities, including Users):
from telethon import utils
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = utils.get_display_name(chat_from)
get_display_name() actually gets a name that you would see. Works for types User, Channel, Chat
That method shall not have await

How to get chat_id, user_id and time from telegram bot?

I am writing a telegram bot to handle conversations (one to one) with users and I am getting same for both userid and chat_id.
My code is:
chat_id = update.message.chat_id
user_id = update.effective_user.id
user_id is the Telegram ID of the user sending a message to bot.
chat_id is the Telegram ID of the chat where a message is being sent to bot.
So, in one to one conversation, the user will send a message in his own chat (with respect to bot). That's the reason both are same.

Creating a twitter bot for a Discord server

I am trying to create a Discord bot that will monitor my twitter feed and post messages into a specific channel on my Discord server. I know solutions already exist for this task (zapier and IFTTT) but I am also wanting to use this as an exercise to develop my coding skills.
I have been following this example but now I haven't been able to get this to run successfully. My problem is that the bot can successfully join the Discord server and monitor my twitter feed but it won't post the message. I have used a print statement (that print(message) line) to determine that the bot does receive new tweets.
I have stored my access tokens and secret keys in another file called twitter_credentials.py (hence that import). I'm using the Tweepy and discord.py libraries, any help will be greatly appreciated - The code below uses << redacted >> identifying strings:
import tweepy, discord
import twitter_credentials
twitter_access_token = twitter_credentials.access_token
twitter_access_token_secret = twitter_credentials.access_token_secret
twitter_consumer_key = twitter_credentials.consumer_key
twitter_consumer_secret = twitter_credentials.consumer_secret
discord_token = twitter_credentials.token_twitter_bot
client = discord.Client()
class StdOutListener(tweepy.StreamListener):
""" A listener handles tweets that are received from the stream.
This is a basic listener that just prints received tweets to stdout."""
def on_status(self, status):
if not status.in_reply_to_status_id == None:
message = '#{0} : {1}'.format(status.in_reply_to_screen_name, status.text)
else:
message = '{0}'.format(status.text)
print(message)
channel = client.get_channel('<<channel_id>>')
em = discord.Embed(title='Tweet', description='My Twitter Feed', colour=0xDEADBF)
em.set_author(name='# <<Twitter_handle>>', icon_url=client.user.default_avatar_url)
client.send_message(channel, message, embed = em)
#client.event
async def on_ready():
if not client.is_logged_in:
raise Exception('Unable to connect to Discord')
else:
print('Connected to Discord')
auth = tweepy.OAuthHandler(twitter_consumer_key, twitter_consumer_secret, callback = 'oob')
auth.secure = True
auth.set_access_token(twitter_access_token, twitter_access_token_secret)
print('Starting Twitter stream')
stream = tweepy.Stream(auth, StdOutListener())
stream.filter(['<<twitter_ID>>'])
client.run(discord_token)
Thanks
Qui

Forwarding posts from a private channel of Telegram

I have a invite link of private channel, and I wanna forwards (or delivery) posts from this channel to me. My desired pseudo code is like below.
def get_channel(bot, update):
message=update.channel_post.text
print(message)
updater = Updater(my_token)
channel_handler = MessageHandler(Filters.text, get_channel,
channel_post_updates=True, invite_link='http://t.me/aa23faba22939bf')
updater.dispatcher.add_handler(channel_handler)
This works well when my bot is in the channel which I created(invite_link is added for my purpose. I don't know where invite_link should be input). But what I want is that my bot forwards posts from channel in which my bot is 'not' included. I prefer python, but any API will be ok. I searched all the google world but have no clues.. Any tips appreciated.
I found a solution with Telethon library. It works for me(http://telethon.readthedocs.io/en/latest/extra/advanced-usage/update-modes.html)
def callback(update):
print('I received', update)
client = TelegramClient('session', api_id, api_hash,
update_workers=1, spawn_read_thread=False)
client.connect()
client.add_event_handler(callback)
client.idle() # ends with Ctrl+C
In callback function you can filter only channel posts or group messages.
If you want to forward message (of any kind) from channel (doesn't matter if it's private or public) to any other chat:
add your bot to channel (notes that, bots are only added as an admin to channel and have admin privileges)
following code (in python) will do the Forwarding:
from telegram import Bot
def forward(update, context):
chat_id = update.effective_chat.id
bot = Bot(token=TOKEN)
bot.forward_message(chat_id = chat_id,
from_chat_id = channel_id,
message_id = (number))
the above code, will forward message from 'from_chat_id' to 'chat_id' (is the user's chat_id which ask the query)
channel_id is just simply the channel's telegram invite link (which start with #)
message_id is the unique number of the message which is in the channel. If you right-click on the message inside the channel, and select 'Copy Post Link' and paste it somewhere, is something like this:
https://t.me/c/123456789/2040
(123456789 is the link of private channel. If this was a public channel, instead of '123456789', there was channel's public address which starts with #)
the message id is: 2040, not the whole.
refrence: https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.forward_message

Categories

Resources