Telegram check if user is admin - telegram-bot

I am using the telegram bot api to make a bot. I have some commands that can only be sent from admins. Like kick and ban commands. How do I check if the sender is an admin or not? I am using the python-telegram-bot api. I do not want everyone to be able to ban members.

You can use getChatMember method. See following instance:

I have found after searching a bit. The admin status is stored under Telegram.ChatMember.status. It is documented here. It is used by bot.get_chat_member(chat_id, user_id). And then getting status in it.

The other answers are correct, but require an additional call to the API. An efficient solution is to cache the list of admins.
A good solution for this is described here, copied below:
Cached Telegram group administrator check
If you want to limit certain bot functions to group administrators, you have to test if a user is an administrator in the group in question. This however requires an extra API request, which is why it can make sense to cache this information for a certain time, especially if your bot is very busy.
This snippet requires this timeout-based cache decorator. (gist mirror)
Save the decorator to a new file named mwt.py and add this line to your imports:
from mwt import MWT
Then, add the following decorated function to your script. You can change the timeout as required.
#MWT(timeout=60*60)
def get_admin_ids(bot, chat_id):
"""Returns a list of admin IDs for a given chat. Results are cached for 1 hour."""
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)]
You can then use the function like this:
if update.message.from_user.id in get_admin_ids(bot, update.message.chat_id):
# admin only
Note: Private chats and groups with all_members_are_administrator flag, are not covered by this snippet. Make sure you handle them.

Related

Is it possible to blacklist user form using telegram bot?

I'm new to do this kind of project. My goals is to build a telegram bot to forward user(s) message from the bot to a channel. Right now I'm facing that some users abuse to send junk message that disturbs a lot. So, is it possible to blacklist some user from using the bot?
My sourcecode is here Go to GitHub
Bots can't block users (like users can block bots), but you can choose to just not handle updates that come from a specific user id. What I usually do in such cases is to use a telegram.ext.TypeHandler(telegram.Update, callback) where callback looks something like
def callback(update, context):
if update.effective_user and update.effective_user in blocked_users:
# This stops any other handlers in higher groups from running
raise DispatcherHandlerStop
Then register it to a low group for the dispatcher (dispatcher.add_handler(…, group=-1)).
Please have a look at the docs of TypeHandler, DispatcherHandlerStop and add_handler for more info :)
One way to keep track of the blocked_users is to store that list in context.bot_data.
Disclaimer: I'm currently the maintainer of python-telegram-bot.
There isn't any native way to do that, however you can have a list of blocked users (preferably a separate JSON file for that extra modularity) and every time the bot is used, check if the user is in that list:
def start(update, context):
if update.effective_user.id in blacklist:
pass # or do whatever you want

How to change Telegram Bot settings knowing only the token

Someone set up Matterbridge to transfer the contents of a Telegram channel into a Mattermost channel. To do this, they created a Telegram bot.
Unfortunately, the person has disappeared (Covid?), and we don't have full details of the account used to set up the bot.
We do have the Bot Token (from the Matterbridge config file).
Is there any way we can find out more about the bot, change its settings, join it to other channels, etc?
A bot's token allows you to do anything the Bot API is capable of doing. You can check a list of available methods here https://core.telegram.org/bots/api#available-methods.
"Is there any way we can find out more about the bot"
Some limited info, yes. Try calling https://api.telegram.org/botBOT_TOKEN/getMe and /getWebhookInfo.
You might be able to get a webhook url - in case it was set up to use one.
"... change its settings"
Rather not. You'd need access to wherever the bot is hosted. It's not possible to tell exactly without knowing how the bot works. But anything specific found within the bot's processing script/program will not be accessible to you.
"...join it to other channels"
Yes. As answered here. Though it may not be useful to do. Depends on how the bot is set up to work.

JHipster: How to restrict user to access own data with REST

JHipster implements several best practices for authentication and authorization.
Mainly described here: https://www.jhipster.tech/security/.
But I still do not see an example how to design a solution, which does not involve putting user verification logic all over the place for a very common use case.
Let's say you have a WebPage using REST-API like BankAccountResource from JHipster Sample App and you want to restrict this to only ADMIN role or currently logged in User. Let's say you have 50 of such services for your customers: BankAccount, Address, BillingAddress, UserData, Devices... For every resource a GET and UPDATE must be restricted. Also loading device /api/device/{id} might not include user-id.
How do I prevent UserA from loading UserB's device by guessing it's id?
How do I avoid planting that code in every method?
I guess JHipster/SpringSecurity has concept/objects to handle such use cases. Could you point me, explain how to use them please?
Maybe this question helps a little bit: Restrict URL access control by id in jhipster
Spring Security hast PostFilters to check if an object e.g. loaded by a method may be accessed. If you need more control you can use Access Control Lists for fine grained access control.
References:
https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#domain-acls
https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5/#method-security-expressions

Restricting user authentication with Firebase

I'm using Firebase to authenticate the users on my application but, since the app is very early stage, I would like to restrict the login (or registration) to only users that have a specific code.
It looks like there's no option like this and I was wondering if there's any solution that doesn't involve a back-end.
Right now I'm using a specific code in the database that the user has to enter while logging in. If that code is not correct you can't login. The problem is the function (obviously) is executed on the front-end so a person with the right knowledge could easily modify the code and still access without token.
Is there a more robust solution?
if you truly want no back end, you can see my answer at the bottom here How to protect firebase Cloud Function HTTP endpoint to allow only Firebase authenticated users? , which involves taking advantage of the fact that every firebase project is also a Google cloud platform project and GCP allows for private functions.
however, there is an easier way: just wrap your cloud function logic with an if clause that checks for any of a number of things before actually executing the function
assuming, for instance, you're on the web platform, when someone invokes an HTTPS callable function from the front, it will be sent with data and context objects.
you could check for context.auth.email to restrict to specific users. or you could check for data.mySecretKey and since the check is occurring in your cloud function, no one could inspect your code to find the key.

How do we use Django-allauth with lazysignup

I'm using Django-allauth for social and simple login. I want that when a user who hasn't signed up or isn't logged in makes a shortlist of items, the shortlist is still present when the user signs up or logs in. So I'm using Django-lazysignup.
Right now, a new lazy_user is created everytime I'm not logged in with Facebook, or it gives me a "column user_id not unique" error. The shortlist is also not converted.
How do we integrate the two? Or how do we do this without using lazysignup?
Any help on this would be great, thanks!
Have a look here:
https://github.com/pennersr/django-allauth/blob/327f5b60f31e9b3db18d461266084a44f04888dc/allauth/account/adapter.py#L117
and here:
https://github.com/pennersr/django-allauth/blob/327f5b60f31e9b3db18d461266084a44f04888dc/allauth/socialaccount/adapter.py#L40
Here, a new User instance is created for local and social users respectively. These adapter methods can be overriden, and instead of spawning a new instance they could be changed to return an existing lazy user instance.
With django-allauth out of the box you will probably run into the problem that you don't have access to the request instance here, but I am willing to adapt allauth to match your use case...
You could use a custom user model (Django 1.5) tweaked in a way, so that it uses the session key as identifier for example.
Later on signup.. just fill in the username and/or email etc.
This could make sense if you want to save the lazy users interactions even if they do not sign up (e.g. for statistical usage). I have not tested this.. but it might work. :)