Aiogram bot to answer my message in private chats but to reply my message in group chats - telegram

for telegram api, Message.reply_html("Hello") has quote which defaults to True in groups and False in private chats (https://docs.python-telegram-bot.org/en/v20.0a4/telegram.message.html#telegram.Message.reply_html). Does aiogram have similar features?
Basically I want the bot to not reply my message in private chats but reply my message in group chats. This is because when creating discussion groups in channels, in order for the bot's reply to be shown in the discussion group, it has to reply to the message of the one who sent the message.
I know that aiogram has both message.reply which replies to the user regardless whether hes in a group or not and message.answer which answers the user regardless whether hes in a group or not too. Theres also a chat type filter which filters messages to private user vs messages to supergroup but to do that, I will need to repeat my code twice which is kinda pointless right when the only difference is a message and a reply?
I tried message.reply('text', reply=False) but that just removes the reply from both groups and private chat, which is equivalent to just message.answer. Any help is appreciated! Thanks!

sorry for my bad English. Aiogram has Filters, namely aiogram.dispatcher.filters.ChatTypeFilter, which inherits BounbdFilter. With which we can create customizable filters for our tasks. More information you can found in documentation. I wrote simple example of a bot that works only in a group. In private chat he doesn't works.
from aiogram.dispatcher.filters import BoundFilter
from aiogram import types
# filter.py
class IsGroup(BoundFilter):
async def check(self, message: types.Message) -> bool:
return message.chat.type in (
types.ChatType.GROUP,
types.ChatType.SUPER_GROUP,
)
# handlers.py
#dp.message_handler(IsGroup(), content_types=types.ContentType.NEW_CHAT_MEMBERS)
async def new_member(message: types.Message):
members = ", ".join([m.get_mention(as_html=True) for m in message.new_chat_members])
await message.reply(f"Hello, {members}.")
We are creating a chat and if we add new member bot wrote "Hello, {member}". And if you want use bot only in a chat you need add in the decorator #dp.message_handler IsGroup() And make it the first argument

Related

how to know where user starting chat? from inside group or from inside bot directly?

I have created telegram bot using telegraf.js
The bot is working correctly, however I need to handle a different thing if the user send message from inside bot directly, let's say the bot should replay with help commands documentations (for example).
the question is:
how to recoginze where the user start chatting? from inside chat group or from inside bot directly?
I tried
var groupInfo =await ctx.telegram.getChat()
without success
I thing the solution would be simple, but I can't find it till now.
thank you in advanced.
You should checkout Telegram docs for Chat type. It has a field called Type and according to the docs:
Type of chat, can be either “private”, “group”, “supergroup” or “channel”
So in telegraf.js you can check the field this ways:
bot.on('text', (ctx) => {
return ctx.reply(`Chat type is: ${ctx.message.chat.type}`)
})
In your case, ctx.message.chat.type == "private" would be messages that are sent to your bot privately and ctx.message.chat.type == "group" or ctx.message.chat.type == "supergroup" are messages sent to groups.

pyTelegramBotAPI message handlers can't see photo

I need my telegram bot to forward messages from the private chat to the customer care staff group.
I run this code:
#bot.message_handler(func=lambda message: message.chat.type=='private')
def forwarder(message):
bot.forward_message(group, message.chat.id, message.id)
bot.send_message(group, '#id'+str(message.chat.id))
It works smoothly with text messages, but does nothing with photos.
Even if I remove all previous message handlers, so there is no conflict with them to handle photos, it still keeps doing nothing.
If I use the get.updates() method I can check "manually" if the photo has arrived and I find it.
Edit: Even if i just run this code only
import telebot
bot = telebot.TeleBot("MY TOKEN")
#bot.message_handler(func=lambda message: True)
def trivial(message):
print('yes')
bot.polling()
I get 'yes' for text messages and absolutely nothing, not even raised exceptions for photos.
If you add content_types as a parameter you will receive whatever is specified in the argument (which takes an array of strings). Probably the default value for that parameter is set to ['text']. Which will only listen for 'text' messages.
To get the results you're looking for
your test code will look like:
import telebot
bot = telebot.TeleBot("MY TOKEN")
#bot.message_handler(func=lambda, message: True, content_types=['photo','text'])
def trivial(message):
print('yes')
bot.polling()
And your working code:
#bot.message_handler(func=lambda, message: message.chat.type=='private', content_types=['photo','text'])
def forwarder(message):
bot.forward_message(group, message.chat.id, message.id)
bot.send_message(group, '#id'+str(message.chat.id))
In Telegram Bot API there is a resource /sendphoto
See:
Sending message in telegram bot with images
Try to find the related method in the PyTelegramBotApi.
Or implement the function to send a photo your own (e.g. using requests library in Python). Then you can use it in the message-handlers of your bot, to forward images.

A way to catch if user leave chat teleram bot

i find new_chat_participant or left_chat_participant but that work only in group chat.
I've used the new_chat_members event to know weather a new user joined the bot or not. But seems that this event will not be emitted.
But using the message event I will get the below result:
{"message_id":4,"from":{"id":324299944,"is_bot":false,"first_name":"foo","last_name":"bar","language_code":"en"},"chat":{"id":324299944,"first_name":"foo","last_name":"bar","type":"private"},"date":1513786467,"text":"/start","entities":[{"offset":0,"length":6,"type":"bot_command"}]
i write bot with java script and in the google app script .
my oreginal problem is how to find out a user stop or left the bot
For some reason that I was not able to find in the docs telegram doesn't send updates when user leaves the private group. It only does it for public groups (ex supergroups). Another curious thing is that the update message contains "left_chat_participant" and "left_chat_member" objects with the exact same info, probably for some bc
unfortunately currently there is no way to found out the user block the bot. new_chat_participant or left_chat_participant presented in telegram bot API v3 for completely another purpose.

Get TELEGRAM Channel/Group ID

Let's say, I've joined TELEGRAM group...
I am just a typical member of GROUP (and thus, cant use any bots there.. ?) so, I am unable to find out the way, how to get GROUP ID.
New Update
Just Simply Forward a message from your channel to This Bot: (https://telegram.me/getidsbot)
Update
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup
bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm
Node.js:
Try using TelegramBot#getChat():
bot.getChat("#channelusername").then(function(chat) {
// 'chat' is a Chat object
console.log(chat.id);
});
See API getChat() method and Chat object.
Hope that helps.
There is a unofficicl Plus Messenger client for Android users, and you can see ID in group/channel info.
Supergroup and Channel will looks like 1068773197, which is -1001068773197 for bots (with -100 prefix).
If you just want to obtain channel/user ID, forward message to #RawDataBot.
there are lots of ways to do so.
simplest one: download plus messenger which is a fork of telegram. it shows every channel's id in the about page of that channel.
https://play.google.com/store/apps/details?id=org.telegram.plus&hl=en
thanks to #Sean:
Supergroup and Channel will looks like 1068773197, which is -1001068773197 for bots (with -100 prefix).
Above method works for channels, for groups you may use this method:
Just forward a single message from that chat to #RawDataBot. it will reply you with a json data containing chatid.
via code:
If you are a member of a group, you should receive updates from that group when ever there is any activity from that group. The updates will contain a chats list-element from which you can get a Channel which has the following relevant fields:
id: group_id,
title: "the_group_title",
username: "group_username"
As of my experience ,there are two popular libraries,
python-Telethon --->Telegram Client Library(uses api_id,api_hash)
python-Telegram-bot ---->Telegram Bot (uses api token)
There are lot of ways to get the user_id ,group_id,channel_id .
To get the these ids use Telethon client library
from telethon import TelegramClient,sync
api_id="xxx" #get from telegram website
api_hash="yyy" #get from telegram website
client=TelegramClient(session_object,api_id,api_hash)
client.start()
#To get the channel_id,group_id,user_id
for chat in client.get_dialogs():
print('name:{0} ids:{1} is_user:{2} is_channel{3} is_group:{4}'.format(chat.name,chat.id,chat.is_user,chat.is_channel,chat.is_group))
That is all about, it will print name and id of channel,group,user.
Also, it will check wheather the id is belong to channel or group or user
generally, Channel id starts with negrative(eg:-1001109500936) starts with (-100)
group id is normal and starts with negative
user id starts with positve
Another way is to use 'plus messanger app'
To see all the group,channel,user id
Cheers
Another Simple Way,
client=TelegramClient(session,api_id,api_hash)
client.start()
destination_entity_name="Type User(may be bot) or group or channel name"
entity=client.get_entity(destination_entity_name)
print(entity.stringify()) #All paratmeters
print(entity.id) #user(bot also considered as user) or group
That should be obtainable using tg-messenger-cli: https://github.com/vysheng/tg I haven't had time to try it out yet but friend has made some automated messages for his daughter. Should be quite versatile.
After hours spent, I was able to find the ID of GROUPS using CuteGram app.
Open group there, and click "COPY" icon, that opens a folder, and in the address you will see the ID.
Invite your bot to your group
and use ur bot to text /myid
then use the GetUpdates api, you shall have your group ID

In python-telegram-bot how to get all participants of the group?

In Python-telegram-bot how to get, if possible, the complete list of all participants of the group at which the bot was added?
You can't with current API but you could the join/exit of user members via it's API.
If you check the Message object you find :
new_chat_participant: A new member was added to the group, information about them (this member may be the bot itself)
left_chat_participant: A member was removed from the group, information about them (this member may be the bot itself)
So with this two information you can track the total number of users in your chat and who they are.
The basic strategy would be to store somewhere (like a database) the occurrences of joining and exiting of users from the group.
When a user join the chat store the object User to the storage.
When a user exit the chat delete the object User from the storage.
Well then do the logic as you need.
Also, latest API update allows you to:
telegram.get_chat_members_count(chat_id): Use this method to get the number of members in a chat.
telegram.get_chat_member(chat_id, user_id): Use this method to get information about a member of a chat.
You can combine with new_chat_participant and left_chat_participant strategy, to build information about a group.
More information here:
https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.get_chat_members_count
https://python-telegram-bot.readthedocs.io/en/stable/telegram.bot.html#telegram.Bot.get_chat_member
As stated by the others before, it's not possible with the bot API (for now) hence you have to go the telegram API way. Start via https://core.telegram.org/api/obtaining_api_id
I had the same problem and solved it via telethon. A snipped for you to start from:
from telethon import TelegramClient
import asyncio
api_id = 1234 # Your API_ID
api_hash = "1a2b3c456" # Your APP_ID
bot_token = "87319a123b12e321ab1cd" # (via botfather, you can alternatively sign in as a user)
goupid = -120304101020
async def get_users(client, group_id):
async for user in client.iter_participants(group_id):
if not user.deleted:
print("id:", user.id, "username:", user.username)
bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
with bot:
asyncio.get_event_loop().run_until_complete(get_users(bot, group_id))
(Example via https://gist.github.com/rokibhasansagar/d727fb30ef5a274cf536bea73260887c)

Resources