Telegram Bot Checks Rather Mentions Is User Or Group Chat - python

I'm trying to code a python anti-advertising telegram bot and basically want to check when a user mentions another user in their message it will check rather the mentioned # is a user or a group.
I want the members to still be able to mention other usernames like ex: #username, but when they mention a group #testinggroup, it will be flagged and removed, here's all I have right now.
from telegram import *
from telegram.ext import *
from requests import *
import re
updater = Updater(token="bot_token", use_context=True)
dispatcher = updater.dispatcher
username = re.compile(r'^#[A-Za-z][A-Za-z0-9_]{4,30}$', re.IGNORECASE)
def messageHandler(update: Update, context: CallbackContext):
#chat_member = context.bot.get_chat_member(update.effective_chat.id, update.message.from_user.id)
#if chat_member.status == 'creator' or chat_member.status == 'administrator' or chat_member.user.is_bot:
# return
if username.search(update.message.text):
return #NEED HELP HERE
dispatcher.add_handler(MessageHandler(Filters.text, messageHandler))
updater.start_polling()
updater.idle()
I've tried everything,
tried removing messages with # in them, but I want users to still be able to mention each other.
tried using regex to detect usernames, but once again want users to be able to mention each other.

Checking if a message contains a mention
Note that you can use Filters.entity("mention") to filter for messages that contain a mention in the form #username - that way you don't have to rely on regex.
Moreover, you can retrieve the usernames via update.effective_message.parse_entities(["mention"]).
Note that MessageEntity.user is not available for entities of type "mention".
Checking if a username links to a private chat or something else
As implied by Lorenzo, you can use get_chat for this. Note that get_chat should return the Chat object in case the username links to a public group or channel. However, for private chats, get_chat only works with the user id and not the username, so get_chat("#privateusername") will raise a "Chat not found" exception rather than returning a Chat object.
Note: The links point to the PTB v13.15 docs. The current stable version is v20.0, which contains significant breaking changes compared to v13.x.
Disclaimer: I'm currently the maintainer of python-telegram-bot.

Related

How to generate OAUTH link for Microsoft Bot framework without using dialogs?

I'm trying to create a sign-in card so that the person interacting with the card is redirected to a sign-in page and the token is then used for other purposes (like fetching information etc).
class SignInGeneratorService:
def __init__(self, APP_ID, APP_PASSWORD):
SETTINGS = BotFrameworkAdapterSettings(APP_ID, APP_PASSWORD)
self.ADAPTER = BotFrameworkAdapter(SETTINGS)
activity = Activity()
self.turn_context = TurnContext(self.ADAPTER, activity)
async def generate_raw_link(self):
return await self.ADAPTER.get_oauth_sign_in_link(self.turn_context, "ADAuth")
This is what I initially tried to get the sign in link, but it doesn't seem to work (probably because we are using a dummy turn context object). Any ideas on how to do the same without having to use dialogs?
Unless I'm misunderstanding your question, I think you can achieve this using the "signin" card. The 06.using-cards sample demonstrates how to set up the card. And, visiting the BotFramework-WebChat repo, you can test this using the 01.getting-started/a.full-bundle demo. Just type in the word "signin" and the card will be presented. Clicking the button brings you to a page to log into Microsoft's live.com site.
You would only need to update the URL so it points to the service of your choice or design allowing you to acquire whatever information necessary.
Hope of help!
Sharing what worked for me. I had to pass MicrosoftAppCredentials and set the bot identity using the bearer token I had created earlier using the Microsoft login API (needs the client id and secret for generating this). After this I was able to create a sign-in URL which could be passed on for further use.
identity = await self.ADAPTER._authenticate_request(self.activity,
"Bearer *bearerToken*")
self.app_credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
self.turn_context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = identity
sign_in_resource = await self.ADAPTER.get_oauth_sign_in_link(self.turn_context, "ADAuth", None, self.app_credentials)

How to validate discord user ids?

I am currently working on a discord.py rewrite bot with a few moderation features such as ban, kick and as the problem is right now unban I need a way to validate that inputted discord ids are valid and not for example strings, too short too long.
Depending why you want to validate the input (I'm going to assume here that you just want trying to unban a user that doesn't exist to not raise an error), you can just call it anyway. Presumably the steps you are doing is somewhat like get user then user unban you can just use some try-catches like the following:
try:
int_id = int(string_id)
user = bot.fetch_user(int_id) # this should likely be async
# whatever code you are already using here to link user id to a server
# member or using the guild context route
except ValueError: # Python error if you cast a non-numeric string to int
print(f"{string_id} is not a well-formed id.") # is not a number
except NotFound: # # Discord error if there is no user for given id
print(f"{int_id} is not a valid id.") # is a number but not a user
except HTTPException: # Discord error if could not contact server
print(f"{int_id} could not be fetched.") # nothing to do with id

How I can send user's location in telegram with aiogram?

I already tried search this in Google. But I couldn't find the answer. I want to bot send user's location. Here is the final version(It doesn't work):
markup_request = ReplyKeyboardMarkup(resize_keyboard=True).add(
KeyboardButton('Send your contact ☎️', request_contact=True)
).add(
KeyboardButton('Send your location 🗺️', request_location=True)
)
#dp.message_handler(commands=['location'])
async def message_for_start(message: types.Message):
await message.reply('Location', reply_markup=markup_request)
Firstly, check your imports.
Secondly, use other methods, instead of try <send_message> or . Reason is updating of aiogram library.

receiving emails with python api O365

I am just starting out in Python and I am trying to accomplish a manual task I have heard is on the simpler side to accomplish with python. My company uses Office 365 for their emails and I want to retrieve an email attachment and store it locally so I can save time . So far have established how to send a simple email, call the names of the folders in my account but I cannot figure out how to read any specific email .
my idea goes a little like this ,
from O365 import Account, message,mailbox
credentials = ('username', 'given password')
account = Account(credentials)
mailbox = account.mailbox()
mail_folder = mailbox.inbox_folder()
mail_folder = mailbox.get_folder(folder_name='Inbox')
print(mail_folder)
#_init__(*,parent= Inbox, con=None,**kwargs)
Message_body = message.body()
message.get_subject('email subject here!')
print(Message.body)
right now I am lost and trying anything within the O365 documentation page but the message module does not have the attribute subject according to how I am using it . Any guidance would be much appreciated
From your example - it's not clear if you are authenticated or not...
If you are then you will be able to list the mailbox folders. In the case below - you can access the inbox and then list the sub-folders:
from O365 import Account, Connection, MSGraphProtocol, Message, MailBox, oauth_authentication_flow
scopes=['basic', 'message_all']
credentials=(<secret>, <another secret>)
account = Account(credentials = credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
account.authenticate(scopes=scopes)
account.connection.refresh_token()mailbox = account.mailbox()
inbox = mailbox.get_folder(folder_name='Inbox')
child_folders = inbox.get_folders(25)
for folder in child_folders:
print(folder.name, folder.parent_id)
This part will allow you to list folders (and also messages).
If I look at your code - it looks as though you are trying to do both?
Try doing something like the following to get the hang of paging through your inbox:
for message in inbox.get_messages(5):
if message.subject == 'test':
print(message.body)
Note that I'm looping through the first 5 messages in the inbox looking for a message with subject 'test'. If it finds the message - then it prints the body.
Hopefully this will shed a little light.

How to send python output to telegram CHANNEL not to Group and gmail email group

Hi I have a program in python that generates results every one hour. The result can be of anything.This program will run in local machine or in the virtual private network.
I have two requirements
1. Send this python generated result to one telegram group [Group name "ourworld"](created by me) automatically without user intervention . (I have desktop telegram client running or web.telegram.org running in the same system)
Send this result to gmail group email ID.
what are the methods available to achieve this requirement .Is there any working code available to do this job .Please share the info and details.
Edit:
The Issue that i am facing :
1.created a Bot using BotFather.
2.Adding this Bot to my Group ,Here i get an error could not add an member So added the Bot as admin in the group
3.Token of the BOT noted down.
4. Trying to get ChatId
in this forum (https://web.telegram.org/#/im?p=g154513121) someone says number after p=g is the chartid ,In my case there is no
number it shows #testingname like this.
Using this approach trying to get the Chat ID https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/getme
so here 738909732 become a chat Id (in this case why we need seperate
call for the chart id)
here it is true as response coming! Here the chat id is the ID of the my "testingname" no chart id generated for the group.
6.Now packing the URL to see the response i am getting this error.
https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/sendMessage?chat_id=738909732&text=testing
the output if i run this in browser
{"ok":false,"error_code":400,"description":"Bad Request: chat not
found"} {"ok":false,"error_code":403,"description":"Forbidden: bot
can't send messages to bots"}
How to resolve this issue and make the BOT working .why i am not able to add BOT to my group that says error "Cant Add user"
How to make this telegram group working.
Note : Using BotFather BOT created
In case for sending message to telegram group the above method provided by bipin_s works where the chat_id = -xxxxxx is used.This is correct id followed by - symbol to be used.
For Posting message in the "telegram channel " a minor change needs to be done in the URL.The URL must be framed as below .
url = "https://api.telegram.org/botTokenID/sendMessage?chat_id=#yourChannelChatID&text=message"
Replace the TokenID with your BOT tokenID replace the yourChannelChatID with your channel chart id.Please note that the channel id is not negative id.
the code will look like this
import request
url = "https://api.telegram.org/botXyz:wwwwDFSJSJSAX/sendMessage?chat_id=#telechanneltesting&text=message"
requests.post(url)
Here the "message" as in the URL it will be posted in telegram channel.
How to get channel id ?
Go to https://web.telegram.org/#/im in browser ,after login now search your "channel".Now in the browser address bar you will one link like https://web.telegram.org/#/im?p=#llliopppppsssssr
p=#llliopppppsssssr after the equal symbol what comes is channel chat ID.
to send message to the telegram "group" without any user intervention , you require a telegram bot. create one using telegram bot-father. take a look at this link. also note the token while creating the bot. This method will work only for telegram Group .Telegram channel another method to be followed which MarxBabu answered below in his answers post.
import requests
# telegram url
url = "https://api.telegram.org/bot<Token>"
def send_mess(text):
params = {'chat_id':-xxxxxxx, 'text': text}
response = requests.post(url + 'sendMessage', data=params)
return response
send_mess(result_you_want_to_send)
to get the chat_id follow the steps mentioned here. note: group chat id's always starts with '-' . e.g. of group chat_id -356163873. A token and chat_id is only what you require to send message to telegram group.
for sending group emails you have to search more as i do not know much
I have it running on a Raspberry pi. You must look for botfather to get your telegram token.
import telepot
from telepot.loop import MessageLoop
telegram_token = 'xxxx:xxxxxx'
user = 4444444
bot = telepot.Bot(telegram_token)
bot.sendMessage(user, 'Hey!')
For configuring gmail I don't have something here right now...
You can send emails in python through SMTP or using the Mailgun Api
I personally prefer using Mailgun as it is easier to setup and sending an email is as easy as sending a post request to mailgun.
You can get the free version of the api and add your group email id to the sandbox (to avoid spam) and then use requests to post an email with the given api token

Categories

Resources