Disconnecting users from a Channel if guess is wrong DiscordPy - input

I'm coding a Discord bot. I made this command where it plays a little guessing game with a random integer from 1 to 10. If the guess from the user is correct, just a message pops out. If not, it disconnects the user from the voice channel, if it's in one.
This is the code I'm working on:
#bot.command()
async def adivinar(ctx: commands.Context):
user = discord.Member
aleatorio = random.randint(1,10)
await ctx.send(f"Guess a number from 1 to 10")
msg = await bot.wait_for("message")
if int(msg.content) == aleatorio:
await ctx.send(f"Congrats! My number was {aleatorio}")
else:
await ctx.send(f"Nope. My number was {aleatorio}")
await user.move_to(None)
This code doesn't work. It shows this error in the terminal:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: move_to() missing 1 required positional argument: 'channel'
In order to make the "adivinar" command, I look into this piece of code as reference that works wonderfully:
#bot.command()
async def kick1(ctx: commands.Context, user: discord.Member):
await ctx.send(f'{user.mention} has been kicked from {user.voice.channel.mention}')
await user.move_to(None)
I'm pretty sure this is very easy to solve. But at the moment it's kinda hard for me to figure it out. Thanks!

you assigned user to the discord.Member class, not to a real member
user = discord.Member
you need to do something like ⬇ to can move it
user = ctx.guild.get_member(1234) # user id
in your case you can also use user = msg.author

Related

Telegram bot unban command

This is my code to unban a user by replying to a message previously left by the user in the bot. But I also want to implement the /unban id command to be able to unban a user by their id. But I don't know how to do it. Please, help.
#bot.message_handler(commands=["unban"], func=Filters.is_answer)
def unblock(message):
user_id = (
Message.select()
.where(Message.id == message.reply_to_message.message_id)
.get()
.from_
)
try:
Block.select().where(Block.user_id == user_id).get().delete_instance()
bot.send_message(user_id, "you have been unbanned"),
except Block.DoesNotExist:
pass
bot.send_message(
message.chat.id, ("{user_id} has been unbanned").format(user_id=user_id)
)
I thought to just read the entire contents of the /unban command through message.text, but I didn’t see any errors, but the command stopped working

Tokens Are Always Invalid

When trying to do a password reset or email confirmation, on the flow to run the method
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
It never returns true. Fails with invalid token, even though I checked the token generated and the one passed via email myself. I am not sure if there is something else I am doing wrong. Below is how I generate the code to send via email
var newUser = await _userManager.FindByEmailAsync(requestData.Email);
var code = await _userManager.GeneratePasswordResetTokenAsync(newUser);
This is the same for sending a confirmation email token. I create the user via api call then try to confirm the email token on the IS server not sure if that adds a wrench in my process or not. I am looking for some help to figure out if my workflow to generate then email the token is incorrect and maybe I should be doing some additional work before.

I want my bot to send an error message if it doesnt have permissions

I'm coding a discord bot in discord.py and i have a question.
I want to have a error handler for when the BOT doesn't have permissions and which permissions the bot is missing. This is the error handler i have now, but i don't know how to do it with the bots permissions and which permission he is missing.
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embe=discord.Embed(title="<:redcross:781952086454960138>Error", description="**Please pass in all required arguments!**", color=0x7289da)
await ctx.send(embed=embe)
elif isinstance(error, commands.MissingPermissions):
embe=discord.Embed(title="<:redcross:781952086454960138>Error", description="**Insufficient permissions!**", color=0x7289da)
await ctx.send(embed=embe)
else:
raise error
So i want the bot to return
embe=discord.Embed(title="<:redcross:781952086454960138>Error", description="**I dont have the right permissions to do that! Please give me {missingpermission}!**", color=0x7289da)
You can use error.missing_perms and by the way, this error is thrown when the invoker doesn't have the permissions not the bot itself.
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"Permissions needed {error.missing_perms}")
If you want the error to be thrown when the bot doesn't have the permissions you need to use the decorator commands.bot_has_permissions(**perms) and in the error handler commands.BotMissingPermissions, here's an example:
#bot.command()
#commands.bot_has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
#kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.BotMissingPermissions):
await ctx.send(f"I don't have the required permissions, please enable {error.missing_perms}")
It's best to read through the docs once beforehand. You can find them here: Docs.
Generally you can cover many events with the error handler in discord.py.
In your case it is a BotMissingPermissions error.
You can handle it with the bot as follows:
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"Permissions needed {error.missing_perms}")
This is just one of many ways to handle this type of error. You can also output a complete list of missing permissions. (kick, ban, manage_channel etc.)

Wit.ai seems to be jumping randomly between stories

I have two separate simple stories on my Wit.ai bot,
the first one takes in the word "Debug", sends "test" then runs a function that outputs context stuff to the console called test_context()
the second one takes in an address, runs a function that changes the context called new_session(), then sends a confirmation of the change to the user structured like "your location has been changed to {address}"
when I type directly into the wit.ai test console it seems to correctly detect the stories and run the corresponding functions, but when I try to use it through the Node.js API it seems to act completely randomly.
Sometimes when typing in an address it will run test_context() followed by new_session(), then output no text, sometimes it will just output the test text followed by the address text and run no functions, sometimes it will act correctly.
The same behavior happens when inputting "Debug" as well.
The back end is set up correctly, as 2 other stories seem to be working perfectly fine.
Both of these stories were working fine earlier today, I have made no changes to the wit stories themselves and no change to the back-end has even touched the debug function.
Is this a known issue?
I encountered this problem as well.
It appears to me as when you do not handle setting context variables in the story from wit.ai correctly (by setting them to null for example), it messes up the story. As a developer it is your own responsability to handle the story correctly "client side", so I can understand wit.ai lets weird stuff happen when you do not do this. Maybe wit.ai decided to jump stories to keep their bot from crashing, still remains a bit mysterious to me. Maybe your problem is of a different kind, just sharing a similair observation and my solution.
Exactly for reasons of testing I created three stories;
handle greetings
tell what the weather in city x is
identify when you want to plan a meeting
The bot is connected to facebook and I handle actions (like planning a meeting) on my nodejs express server.
I said to the bot "I want to plan a meeting tomorrow", resulting in a wit date/time. One timeslot by the way. This is going ok. Then I sent the message "I want to plan a meeting this morning". This resulted in TWO date/time variables in the wit.ai context. In turn, my code could not handle this; two timestamps resulted in null (probably json message getting more complicated and I try to get the wrong field). This in turn resulted in null for the context variable that had to be returned.
So what I did is to catch the error for when the context variable is not filled and just fill in [wit.js could not find date]. This fixed the problem, even though I now of course need to handle this error better.
Old code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
},}
New, working code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
if(myDateTime){
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
} else {
context.appointmentText = '[wit.js could not find date]'
return resolve(context);
}
});
},
Hope this helps

Rails koala "error unsupported get request" after long task - calling FB graph API

After a long task (14s and can be more with more than 600 call to Facebook) my app returns a 500 internal server error with the following description:
Koala::Facebook::APIError (GraphMethodException: Unsupported get request.)
What I do is something like this:
#FBGraph = Koala::Facebook::API.new
tud = MyUsers.all
tud.each do |user|
graph = #FBGraph.get_object(user.fb_user_id)
picture = #FBGraph.get_picture(user.fb_user_id)
thisTud = MyUsers.find(user.id)
thisTud.name = graph["name"]
thisTud.url = graph["link"]
thisTud.url_pic = picture
if thisTud.save
puts "Saved!"
else
puts "Error"
end
end
I receive (on the terminal) all the "Saved!", but after retrieving the data, it does automatically the mysql operations and it fails. And the data is not saved on the DB.
As suggested in this post I have placed the #FBGraph = Koala::Facebook::API.new in a new Thread, but nothing changes.
Note: when I'd do the same operations with less users, all was working good.
How hellvinz says is a facebook bug.
I have find a workaround for now that seems that works:
change this
graph = #FBGraph.get_object(user.fb_user_id)
to this
graph = #FBGraph.get_object("#{user.fb_user_id}?fields=id,name,username,picture,link")
Explicitly declaring the fields seems that solve the problem.
And if this is not sufficient there are 2 more tricks that can resolve the problem:
Calling again after a time delay (for example after an hour), and calling only the requests incomplete
Creating multiple fb app ID and accounts differentiating the requests with the accounts