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
Related
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.
I wanted a bot I wanted the bot when the user wrote the command /add_admin (here is the user id ) And the bot added it either to a separate file or to the code admin = [user id] and I don't know how to do it, I write the code in Replit python
I haven't tried anything because I don't know how
I would store it in a .json file.
Say you created an admins.json in a separate /admins folder, this is how I would set it up:
async def add_admin(ctx, id):
# If you want there to be only one admin
dict = {"Admin": id}
with open('./admins/admins.json', "r+") as f:
json.dump(dict, f)
await ctx.send(f"Noted {id} as admin.")
This is just a simple example of writing into JSON through python. In this instance, the key "Admin" in this dictionary will be updated to any value whenever the command is re-run. If you wanted there to be more than one admin in the JSON, then you'd use something like .update().
so im playing a little bit around with my telegram bot, now im already able to send normal messages and pictures. But now i want to be able to send pre recorded voice messages as an answer. In the documentation it says to use send_voice for this matter and it recommends using the file_id of a file thats already on the telegram servers. So thats what i did i send a voice message to the #RawDataBot and he returned to me the file_id of the voice message.
Problem is: When i try to trigger it i get the following error: telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: wrong file identifier/HTTP URL specified
Any ideas here on what i might be doing wrong? Here is the relevant code:
import telebot
API_KEY = <MY_API_KEY>
bot = telebot.TeleBot(API_KEY)
#start
#bot.message_handler(commands=['start'])
def start (message):
bot.send_message(message.chat.id,Textstart)
#bot.message_handler(commands=['pic'])
def start (photo):
bot.send_photo(photo.chat.id, "https://de.wikipedia.org/wiki/Zeus#/media/Datei:Zeus_Otricoli_Pio-Clementino_Inv257.jpg")
#here is the part where he is supposed to send the voice message if someone types in /audio
#bot.message_handler(commands=['audio'])
def start (voice):
bot.send_voice(voice.chat.id,"AwACAgIAAxkBAAEWjl5i5bjyudWAM9IISKWhE1Gjs5ntQgACLx8AApcNKEv97pVasPhBoCkE",)
bot.polling()
There are multiple reasons, but I think it is because of these:
file_id is unique for each individual bot and can't be transferred from one bot to another.
file_id uniquely identifies a file, but a file can have different valid file_ids even for the same bot.
See here.
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
I am developing an application with Django. In forms.py, where the classes for my forms are stored, I have written a clean function to verify that all the emails typed into a textbox adhere to the proper format (person#site.com).
In this clean function, I build the email message with an EmailMessage object:
def clean_recipients(self):
rec = self.data['recipients'].split(",")
recList = []
for recipient in rec:
reci = str.strip(str(recipient))
recList.append(reci)
message = (self.data['subject'], self.data['message'], 'hi#world.com', recList)
mail = EmailMessage(self.data['subject'], self.data['message'], 'from#somebody.com', ['email_list#mysite.org'], recList)
try:
mail.send(fail_silently=False)
except Exception:
raise forms.ValidationError('Please check inputted emails for validity.')
return self.data['recipients']
However, the exception 'Please check inputted emails for validity.' is never raised on the form regardless of what I input into the textbox. If I input random characters into the textbox, simply no message is sent.
What is the proper way to catch if the email was not sent properly?
Thank you.
Try to clean recipients emails format only in the clean_recipients. There is snippet how to check email. http://djangosnippets.org/snippets/1093/ . Raise validation error if email format does not match.
Create email and send it from the form's clean method (if you need show sending errors. You will need check for form errors before send.) or from the view.
PS. get your data this way - self.cleaned_data instead of self.data.