discord py - Bot ignores "if" check - python

I have a weird problem and can't find a solution for it. I want to get the best user from my JSON leaderboard and it's working. But now I want to check if the message.author and the user from the leaderboard have the same User-ID. If yes, then an action should run.
My code:
with open("level.json", "r") as a:
level = json.load(a)
high_score_list = sorted(level, key=lambda x: level[x].get('secXP'), reverse=True)
print(f"User2: {high_score_list[0]} + msg author: {message.author.id} - {message.author.name}")
# thats not working
if message.author.id == high_score_list[0]:
embed.set_author(name=f'best leaderboard user!)
embed.color = 0x686de0
Even if the User-IDs are the exact same from the if check, the bot doesn't do it. I tried "print" Lines at the if check, but even this is not running.

I'd assume your issue is with datatypes. Check your json whether the highscorelist has text or number entries. The author's id is always of type int so if your highscore is a string they won't ever be equal.

Related

Python telegram bot - reply when user says specific words

Context: I am starting to learn how to code a telegram bot in python. I have successfully made a fun bot for my group with friends to use. However, i only want it to respond when specific words are mentioned apart from the commands that trigger it.
Example: Whenever a user says the word "wen" plus any other word(s), i want the bot to reply with: SOON!
I want the bot to only pick up some trigger words and reply and for the remainder of the chat to stay idle
Part of my code:
user_message = str(input_text).lower()
wenResponse = str("wen ").join(input_text)
if user_message + wenResponse:
return ("SOON!")
def handle_message(update,context):
text=str(update.message.text).lower()
response=sample_responses(text)
update.message.reply_text(response)
Actual result:
The bot is working but only when the user says specifically "wen". If the user adds more words after "wen" the bot doesnt pick it up.
You can just use .startswith('text') to check is a string starts with 'text'.
The .startswith('text') return True if the string starts with text, or else it will retur False.
if "wen" in str(input_text).lower():
return "soon"
This should work even if the key word isn’t the first word.

Python list.append not working. I'm using discord.py and replit database to make a gambling bot and I wanted a list of participants

So basically I'm trying to get a discord betting bot to give a list of participants that it can cycle through when games end. The problem is that when I use this code it doesn't seem to append. I've tried debugging it using an alt. The not in db['list'] part triggers fine, and there are no errors raised, but the list still only contains my main account's ID (which was used to create the list.)
The repl.it database is basically a big array with string indexes / keys. I'm sure that lists are an accepted data type since when I debugged before it printed db['list'] as ['#MYIDNUMBER'] but it still won't append my alt's.
db['list'] = [str(message.author.id)]
db['betenable'] = True
if message.content.startswith('$createaccount'):
db[str(message.author.id)+'wallet'] = 1000
db[str(message.author.id)+'ingame'] = 0
db[str(message.author.id)+'bet'] = 'No Party'
if str(message.author.id) not in db['list']:
db['list'].append(str(message.author.id))```
You're accessing db[list], using the list built-in, instead of the string, db['list'].

(discord.py) What is the correct way of checking if a message contains an element from a list?

I'm trying to make a profanity filter for my bot. I allowed server admins to make their own list of bad words which my bot uses for their server. In the on_message function I used this code to check if a user's message contains a word from the filter:
file = open(f"configs/antiswearvalues/customantiswear/{message.guild.id}.txt")
res = [ele for ele in file.read() if (ele in message.content)]
if bool(res):
await message.channel.send("you did a bad. time for the boot.")
The problem is the bot still said you did a bad. time for the boot. even if the message contained a snippet from the elements and not an entire element.
So if the list was ['omg', 'crap', 'hell'], the bot would still warn the user if their message contained h or cr because hell and crap contain those.
My question is: How can I make my bot properly check if a user's message contains an element from a list?
You should consider using json. Getting a word blacklist will be way easier than parsing a txt file without using any library:
Your json file (eg. blacklist.json):
['omg', 'crap', 'hell']
Your python code:
from json import loads
#client.event
async def on_message(message):
with open("blacklist.json", "r"):
data = loads(file.read())
for word in data:
if word in message.content:
await message.channel.send("you did a bad. time for the boot.")
return
Your code isn't working as intended because you didn't parsed your file data, you were exploring a string, not a list.

My Discord XP bot isn't recognizing user data in JSON files?

My bot is not working as planned.
For the context of the bot, I followed a YouTuber's tutorial almost exactly (other than the algorithm for the experience) - https://www.youtube.com/watch?v=pKkrCHnun0M&t=890s
async def update_user(users, user):
if not user.id in users:
print('added new user')
users[user.id] = {}
users[user.id]['experience'] = 0
users[user.id]['level'] = 1
async def add_xp(users, user, exp):
print('added exp')
users[user.id]['experience'] += exp
I added the print function so I could track which functions have been triggered.
The first time, it worked. User data popped up in my users.json file when i typed in the channel. However, upon the second time typing anything, this happens:
It showed the same data being input twice! I was so confused because everything is the same. I will post the full code of the bot in here. Please help me make the bot possible to use.
https://pastebin.com/BkzSbVan (I removed the server ID and channel ID, so please focus on the functions)
The JSON standard requires keys to be strings, so when you use json.dump, it converts the integer IDs into strings. However, when you load that back with json.load, it stays a string, so the user dictionary will have string keys when you load it from the file. Then, when you check if the user ID is in the dictionary, it's by integer, so it's not, and it adds the integer ID as a key for the dictionary with a new initial value. At this point, you have an integer and string version of the same ID in your dictionary. When you write this back to the file with json.dump, it again converts the integer ID to a string, resulting in what you see in your screenshot.

How can I properly parse for a tagged user in my Discord bot?

I am adding profile cards onto my Discord bot, but I've come across one issue. When someone types !profile #user I am not sure how to properly parse for #user so the bot knows which profile card to lookup.
I first parse message.content and then remove the 9 first chars of the message content (which is always !profile) but the rest of the message content returns the user_id which looks <#289583108183948460> instead of the user's discrim. I have tried using re.sub to remove the special characters (#, >, and <) like this:
a = str(message.content[9:])
removeSpecialChars = re.sub("[!##$%^&*()[]{};:,./<>?\|`~-=_+]", " ", a)
print(removeSpecialChars)
But the weird characters are still there when I only want the number so I can search it in the database easily. I'm sure there's a way better way to do this though but I can't figure it out.
discord.py's message objects include a Message.mentions attribute so you can iterate over a list of Member. Here are the doc listings for async and rewrite.
With this you can simply iterate over the mentions as so:
for member in ctx.message.mentions:
# do stuff with member
what you actually want
discord.py allows you to grab discord.Member objects from messages with type hinting. simply add the following to the command
#bot.command()
async def profile(ctx, member: discord.Member=None):
member = member or ctx.message.author

Categories

Resources