How do you check if a string is convertible to an int, and if so, convert it? (Python, involves discord.py rewrite) - url-rewriting

I'm currently making a discord bot in Python. I want to make a command where you have two options for an argument:
An integer to delete a certain amount of messages
And the word 'all' (a string) to delete all the messages in the channel.
I've tried functions like this to determine if it is a string or not...
def isint(s):
try:
int(s)
isint = True
except ValueError:
isint = False
return isint
... but it returns this error:
TypeError: '<=' not supported between instances of 'str' and 'int'
This is the current, most recent code for the command that I have tried:
#commands.command()
#commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
number = isint(amount)
if number == False:
if amount == 'all':
await ctx.channel.purge(limit = inf)
else:
await ctx.send('Invalid amount.')
if number == True:
await ctx.channel.purge(limit = amount)
else:
await ctx.send('Invalid amount.')
The full traceback for the error, in case it is relevant, is the following:
Traceback (most recent call last):
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\44794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<=' not supported between instances of 'str' and 'int'
Please bear with me here, I am very new to Python.
EDIT:
Thanks for helping me with this! Here is the code I used in case anyone else needs it:
def is_int(x):
if x.isdigit():
return True
return False
#commands.command()
#commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
number = is_int(amount)
if number == False:
if amount == 'all':
await ctx.channel.purge(limit = inf)
else:
await ctx.send('Invalid amount.')
if number == True:
amount = int(amount)
await ctx.channel.purge(limit = amount)
else:
await ctx.send('Invalid amount.')
Again, thanks for helping me out!

You're able to use the string's .isdigit() method.
Bear in mind that this will return False for negatives:
>>> my_str = "123"
>>> my_str.isdigit()
True
>>> other_str = "-123"
>>> my_str.isdigit()
False
Working example:
def is_int(some_value):
if some_input.isdigit():
return True
return False
some_input = input("Enter some numbers or words!\n-> ")
print(is_int(some_input))
Reference:
str.isdigit()

Try use this instead of your function isint:
# clear function
number = amount.__class__.__name__ == 'int'

Related

How do I make a discord music bot play the first search result from lavalink?

I have made a discord music bot using python, lavalink and wavelink. I have made it according to a tutorial where it plays the songs I select from a list of search results. I want to make the bot play the first search result directly instead of me having to select from the list? I have tried to check other tutorials and codes but implementing them doesn't seem to work as their full codes for the classes or they involve ffmpeg or ytdll.
async def add_tracks(self,ctx, tracks):
if not tracks:
raise NoTracksFound #Goes to a pass command
if isinstance(tracks,wavelink.TrackPlaylist):
self.queue.add(*tracks.tracks)
elif len(tracks) == 1:
self.queue.add(tracks[0])
await ctx.send(f"{tracks[0].title} added to list")
else:
if (track := await self.choose_track(ctx, tracks)) is not None:
self.queue.add(track)
await ctx.send(f"Added {track.title} to list")
if not self.is_playing:
await self.start_playback()
async def choose_track(self, ctx, tracks):
def _check(r, u):
return (
r.emoji in OPTIONS.keys()
and u == ctx.author
and r.message.id == msg.id
)
embed = discord.Embed(
title="Choose a song",
description=(
"\n".join(
f"**{i+1}.** {t.title} ({t.length//60000}:{str(t.length%60).zfill(2)})"
for i, t in enumerate(tracks[:5])
)
),
colour=ctx.author.colour,
timestamp=dt.datetime.utcnow()
)
embed.set_author(name="Query Results")
embed.set_footer(text=f"{ctx.author.display_name} kaettan", icon_url=ctx.author.avatar_url)
msg = await ctx.send(embed=embed)
for emoji in list(OPTIONS.keys())[:min(len(tracks), len(OPTIONS))]:
await msg.add_reaction(emoji)
try:
reaction, _ = await self.bot.wait_for("reaction_add", timeout = 60.0, check =_check)
except asyncio.TimeoutError:
await msg.delete()
await ctx.message.delete()
else:
await msg.delete()
return tracks[OPTIONS[reaction.emoji]]
OPTIONS = {
"1️⃣": 0,
"2⃣": 1,
"3⃣": 2,
"4⃣": 3,
"5⃣": 4,
}
i dont recomand to use lavalink but i have a great music cog file for you to use just get rid of the blacklist user part and if you want it add me on discord RageWire#0001
-From head dev and support team from rage bots
import discord
from discord.ext import commands
from random import choice
import string
from discord.ext.commands.cooldowns import BucketType
import asyncio
import youtube_dl
import pafy
import datetime
from discord_slash import cog_ext, SlashContext
x = datetime.datetime.now()
from ult import *
class music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def pause(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
ctx.voice_client.pause()
await ctx.send("*Paused -* ⏸️")
#commands.command()
async def resume(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
ctx.voice_client.resume()
await ctx.send("*Resuming -* ▶️")
#commands.command()
#commands.is_owner()
#commands.cooldown(1, 5, commands.BucketType.user)
async def oskip(self, ctx):
commandd = "oskip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
await ctx.send("skipping")
ctx.voice_client.stop()
await self.check_queue(ctx)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def join(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "join"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def leave(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "leave"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("I am not connected to a voice channel.")
#commands.command()
async def play(self, ctx, *, song=None):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "play"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def search(self, ctx, *, song=None):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "search"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if song is None: return await ctx.send("You forgot to include a song to search for.")
await ctx.send("Searching for song, this may take a few seconds.")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="*You can use these URL's to play an exact song if the one you want isn't the first result.*\n", colour=discord.Color.green())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def queue(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else: # display the current guilds queue
commandd = "queue"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("There are currently no songs in the queue.")
embed = discord.Embed(title="Song Queue", description="", colour=discord.Color.green().dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Thanks for using me!")
await ctx.send(embed=embed)
#commands.command()
#commands.has_permissions(administrator=True)
#commands.cooldown(1, 5, commands.BucketType.user)
async def adskip(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "adskip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
await ctx.send("skipping")
ctx.voice_client.stop()
await self.check_queue(ctx)
#commands.command()
#commands.cooldown(1, 5, commands.BucketType.user)
async def skip(self, ctx):
if await get_mute(ctx.author) != 0:
await ctx.send("You are blacklisted from the bot")
else:
commandd = "skip"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
if ctx.voice_client is None:
return await ctx.send("I am not playing any song.")
if ctx.author.voice is None:
return await ctx.send("You are not connected to any voice channel.")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("I am not currently playing any songs for you.")
poll = discord.Embed(title=f"Vote to Skip Song by - {ctx.author.name}#{ctx.author.discriminator}", description="**80% of the voice channel must vote to skip for it to pass.**", colour=discord.Color.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Stay", value=":no_entry_sign:")
poll.set_footer(text="Voting ends in 15 seconds.")
poll_msg = await ctx.send(embed=poll) # only returns temporary message, we need to get the cached message to get the reactions
poll_id = poll_msg.id
await poll_msg.add_reaction(u"\u2705") # yes
await poll_msg.add_reaction(u"\U0001F6AB") # no
await asyncio.sleep(15) # 15 seconds to vote
poll_msg = await ctx.channel.fetch_message(poll_id)
votes = {u"\u2705": 0, u"\U0001F6AB": 0}
reacted = []
for reaction in poll_msg.reactions:
if reaction.emoji in [u"\u2705", u"\U0001F6AB"]:
async for user in reaction.users():
if user.voice.channel.id == ctx.voice_client.channel.id and user.id not in reacted and not user.bot:
votes[reaction.emoji] += 1
reacted.append(user.id)
skip = False
if votes[u"\u2705"] > 0:
if votes[u"\U0001F6AB"] == 0 or votes[u"\u2705"] / (votes[u"\u2705"] + votes[u"\U0001F6AB"]) > 0.79: # 80% or higher
skip = True
embed = discord.Embed(title="Skip Successful", description="***Voting to skip the current song was succesful, skipping now.***", colour=discord.Color.green())
if not skip:
embed = discord.Embed(title="Skip Failed", description="*Voting to skip the current song has failed.*\n\n**Voting failed, the vote requires at least 80% of the members to skip.**", colour=discord.Color.red())
embed.set_footer(text="Voting has ended.")
await poll_msg.clear_reactions()
await poll_msg.edit(embed=embed)
if skip:
ctx.voice_client.stop()
await self.check_queue(ctx)
def setup(bot):
bot.add_cog(music(bot))

discord.py 'Command.__call__' was never awaited

I keep trying, it was a tutorial. I did exactly what it said. I doubt the next episode will say what's wrong. why do i need so many words ,,,
#client.command()
async def balance(ctx):
await open_account(ctx.author)
user = ctx.author
users = get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title = f"{ctx.author.name}'s balance",color=discord.color.dark_green)
em.add_field(name = "Wallet Balance", value = wallet_amt)
em.add_field(name = "Bank Balance", value = bank_amt)
await ctx.send(embed=em)
#client.command()
async def beg(ctx):
await open_account(ctx.author)
users = get_bank_data()
user = ctx.author
earnings = random.randrange(51)
await ctx.send(f"Someone gave you {earnings} coins!!")
users[str(user.id)]["wallet"] += earnings
with open("bank.json", "w") as f:
json.dump(users, f)
def open_account(user):
users = await get_bank_data()
with open("bank.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["wallet"] = 0
users[str(user.id)]["bank"] = 0
with open("bank.json", "w") as f:
json.dump(users, f)
return True
def get_bank_data():
with open("bank.json", "r") as f:
users = json.load(f)
return users
but with this error
z:\DBot\bot(1.2).py:108: RuntimeWarning: coroutine 'Command.__call__' was never awaited
with open("bank.json", "r") as f:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
i don't know what to do. Sorry my questions are bad because i just want someone to answer them, dont have time to make them good
open_account() and get_bank_data() are not required be asynchronous functions,
You can use def open_account(user) and def get_back_data().
If you do that, you should remove await while calling those two functions.

What is wrong with my search for money code in discord.py

I need help fixing my code
#client.command
#commands.cooldown(5, 20, commands.BucketType.user)
async def search(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
peen = users[str(user.id)]["wallet"]
tu = random.randint(19, 157)
rand = random.choice(hs)
embed54=discord.Embed(title='Search in...', description=f'{rand}, {rand}, {rand}')
embed54.add_footer('Do !beg for money as well!')
await ctx.send(embed=embed54)
await client.wait_for(rand)
def check(m):
return m.author == ctx.author and m.channnel == ctx.channel
embed53=discord.Embed(title='You Found...', description=f'${tu} From {ctx.message}')
await ctx.send(embed=embed53)
fa = tu
peen += fa
why does it not work
SyntaxError: 'await' outside async function
i need help
pls it gives error every time so help me
also yeah boi
Since I don't know what hs means or how you defined it I omitted the whole thing once and replaced it with a simple number just for my test.
To clarify beforehand: You had errors in creating an embed, in your check function and in your way of rendering with await functions and some typos.
This method works fine for me:
#client.command()
#commands.cooldown(5, 20, commands.BucketType.user)
async def search(ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel # New check
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
hs = # DEFINE WHAT IT IS! <<<
peen = users[str(user.id)]["wallet"]
tu = random.randint(19, 157)
rand = random.choice(hs)
embed54 = discord.Embed(title='Search in...', description=f'{rand}, {rand}, {rand}')
embed54.set_footer(text='Do !beg for money as well!') # SET footer
await ctx.send(embed=embed54)
response = await client.wait_for('message', check=check) # Wait for MESSAGE, add check
if response.content == rand: # I assume you want to get the author say one of the numbers
embed53 = discord.Embed(title='You Found...', description=f'${tu} From {ctx.message.content}')
await ctx.send(embed=embed53)
fa = tu
peen += fa
else: # If the number is not in the embed
await ctx.send("You did not respond correctly.")
What did we do?
Re-built your check as it is m.channel and NOT m.channnel, just a little typo here
Added a "real" footer, as embed54.add_footer does not exist, it is embed54.set_footer(text='', icon_url='')
wait_for a 'message' from the author of the message and if rand, which you have to define as I do not know what hs is, is not in his answer he will not get whatever you defined. (if/else statements)
Replaced ctx.message with ctx.message.content as otherwise it will give out a longer "text" than just search
! Since there were many mistakes in your code I would recommend to have a closer look at the docs again !
i actually did this and it worked:
#commands.cooldown(5, 20, commands.BucketType.user)
async def search(ctx):
def check(m):
return m.author == ctx.author and m.channel == ctx.message.channel # New check
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
peen = users[str(user.id)]["wallet"]
tu = random.randint(19, 157)
rand = random.choice(hs)
rand1 = random.choice(hs)
rand2 = random.choice(hs)
embed54 = discord.Embed(title='Search in...', description=f'{rand}, {rand1}, {rand2}')
embed54.set_footer(text='Do !beg for money as well!') # SET footer
await ctx.send(embed=embed54)
response = await client.wait_for('message', check=check) # Wait for MESSAGE, import check
if response.content == rand: # I assume you want to get the author say one of the numbers
embed53 = discord.Embed(title='You Found...', description=f'${tu} From {ctx.message.content}')
await ctx.send(embed=embed53)
earnings = tu
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json","w") as f:
json.dump(users,f)
return True
else:
response = await client.wait_for('message', check=check)
if response.content == rand1: # I assume you want to get the author say one of the numbers
embed53 = discord.Embed(title='You Found...', description=f'${tu} From {ctx.message.content}')
await ctx.send(embed=embed53)
earnings = tu
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json","w") as f:
json.dump(users,f)
return True
else:
response = await client.wait_for('message', check=check) # Wait for MESSAGE, import check
if response.content == rand1: # I assume you want to get the author say one of the numbers
embed53 = discord.Embed(title='You Found...', description=f'${tu} From {ctx.message.content}')
await ctx.send(embed=embed53)
earnings = tu
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json","w") as f:
json.dump(users,f)
return True

I am new to python and i am trying to create a leaderboard

I would like to, as an admin, add points to a specific member's balance
Know how to create a JSON file with all the "points" someone has.
import discord
from discord.ext import commands
import random
import os
import json
# this line of code gives the bot a comand prefix
bot = commands.Bot(command_prefix="/")
# This line of code tells the bot to start up
#bot.event
async def on_ready():
print("The bot is now online!")
#bot.command(pass_context=True)
async def leaderboard(ctx):
await ctx.send("This is a work in progress, this will dieplay the leaderboard")
amounts = {}
#bot.command(pass_context=True)
async def balance(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} ben points".format(amounts[id]))
else:
await ctx.send("You do not have an account")
#bot.command(pass_context=True)
async def register(ctx):
id = str(ctx.message.author.id)
if id not in amounts.keys:
amounts[id] = 100
await ctx.send("You are now registered")
_save()
else:
await ctx.send("You already have an account")
#bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
primary_id = str(ctx.message.author.id)
other_id = str(other.id)
if primary_id not in amounts:
await ctx.send("You do not have an account")
elif other_id not in amounts:
await ctx.send("The other party does not have an account")
elif amounts[primary_id] < amount:
await ctx.send("You cannot afford this transaction")
else:
amounts[primary_id] -= amount
amounts[other_id] += amount
await ctx.send("Transaction complete")
_save()
def _save():
with open('amounts.json', 'w+') as f:
json.dump(amounts, f)
#bot.command()
async def save():
_save()
#This line of code tells the bot to run
bot.run("Token")
I am not sure on what I am meant to do from here.
I might be over complicating the code if anyone can make it more efficient I will be incredibly grateful.
Here's the essential usage and everything you'll need to know for the basics of JSON:
# Creating a dictionary with some values
>>> data = {"foo": "bar", "key": "value"}
# Opening a file and writing to it
>>> with open("db.json", "w+") as fp:
... json.dump(data, fp, sort_keys=True, indent=4) # Kwargs for beautification
# Loading in data from a file
>>> with open("db.json", "r") as fp:
... data = json.load(fp)
# Accessing the values
>>> data["foo"]
'bar'
>>> data["key"]
'value'
This can be adapted to suit your needs, perhaps something like:
# Let's say the JSON has the following structure:
# {"users": {112233445566778899: {"points": 0}, 224466881133557799: {"points": 0}}}
# The "users" key is a bit redundant if you're only gonna store users in the file.
# It's down to what you'll be storing in the file and readability etc.
import json
import random
import typing
def add_points(member_id: str, amount: int):
# Open the file first as to load in all the users' data
# Making a new dict would just overwrite the current file's contents
with open("file.json", "r") as fp:
data = json.load(fp)
data["users"][member_id]["points"] += amount
# Write the updated data to the file
with open("file.json", "w+") as fp:
json.dump(data, fp, sort_keys=True, indent=4)
return data["users"][user_id]["points"]
#bot.command()
async def give(ctx, member: typing.Optional[discord.Member]=None, points:typing.Optional[int]=None):
if not member:
member = ctx.author
if not points:
points = random.randint(10, 50)
# Have a separate getter for the points - this was just for the sake of concise code
total_points = add_points(member.id, points)
await ctx.send(f"Successfully gave {member.mention} {points} points! Total: {total_points}")
I'll be happy to clarify anything if need be.
References:
Dictionary exercises - Might be worth taking a look into so then you're comfortable with how they work.
f-Strings - Python 3.6.0+
json.load()
json.dump()
typing.Optional
User.id
commands.Context
Context.author

How do i check the response from a list

I was creating a bot with codes to enter. But how do i check if the message content contains 1 of the codes in the list?
this is what i have now:
#bot.command(name='get')
async def get(ctx):
await ctx.send('Enter your code')
msg = await bot.wait_for('message')
if msg.content == ['code1', 'code2']:
await ctx.send('Here is your treasure!')
else:
await ctx.send('That code is invalid')
You can use the in keyword:
>>> a = 2
>>> mylist = [1, 2, 3]
>>> a in mylist
True
>>> mylist.remove(2)
>>> a in mylist
False
And applied to your case:
#bot.command(name='get')
async def get(ctx):
await ctx.send('Enter your code')
msg = await bot.wait_for('message')
# converting to lower case - make sure everything in the list is lower case too
if msg.content.lower() in ['code1', 'code2']:
await ctx.send('Here is your treasure!')
else:
await ctx.send('That code is invalid')
I'd also recommend adding a check, so that you know the message is from the original author, in the same channel etc:
#bot.command(name='get')
async def get(ctx):
await ctx.send('Enter your code')
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await bot.wait_for('message', check=check)
if msg.content.lower() in ['code1', 'code2']:
await ctx.send('Here is your treasure!')
else:
await ctx.send('That code is invalid')
References:
Client.wait_for()
Message.channel
Message.author

Resources