Wikipedia Command Discord.py - python

#commands.command()
#commands.cooldown(1,10,BucketType.user)
async def wiki(self,ctx,*,word):
def sum(arg):
definition = wikipedia.summary(arg,sentences=3,chars=1000)
return sum(word)
await ctx.send(sum)
I am making a Wiki command, it doesn't work as expected and responds with this:

That's because you are using sum the wrong way. Instead of this:
await ctx.send(sum)
you have to do this:
await ctx.send(sum(word))
Also, why are you invoking the function from within itself? In sum you should return definition.
Try not to shadow the builtin sum. You should rename the function to be get_definition or something else instead.

Related

PATCH, Update a row with SQLalchemy, project build using Flask and CORS

I hope everything is going well.
I'm working in a project really big and it wasn't set up by me. The project is buils using flask and cors.
I'm trying to create a query to update a row with SQLAlchemy follow the structure that the project has. so basically is like that:
#app.route("/update-topic", methods=['PATCH'])
async def update_by_id():
input_data = request.get_json()
await update_record(input_data)
return ApplicationTopicSchema(many=True).dump(data)
As you see in the code above is just a simple endpoint with PATCH method that get the input data and pass it to a function update_record(), that function is in charge to update the record like you can see in the next code:
from sqlalchemy import and_, update
class AppTopics(Base):
__tablename__ = AppTopics.__table__
async def update_record(self, data):
id_data = data['id']
query = self.__tablename__.update().\
where(self.__tablename__.c.id == id_data).values(**data).returning(self.__tablename__)
await super().fetch_one(query=query)
return 'updated'
Basically is something like that, and when I try to use the endpoint I get the next message error:
TypeError: The response value returned by the view function cannot be None
Executing <Handle <TaskWakeupMethWrapper object at 0x000001CAD3970F10>(<Future f
inis...events.py:418>) created at C:\Python\Python380\lib\asyncio\tasks.py:881>
Also, I'm trying to structure the query in another like this:
from sqlalchemy import and_, update
class AppTopics(Base):
__tablename__ = AppTopics.__table__
async def update_record(self, data):
u = update(self.__tablename__)
u = u.values({"topic": data['topic']})
u = u.where(self.__tablename__.c.id == data['id'])
await super().fetch_one(query=u)
return 'updated'
However I got the same error.
May you guys knows what is happening and what means this error:
TypeError: The response value returned by the view function cannot be None
Executing <Handle <TaskWakeupMethWrapper object at 0x000001B1B4861100>(<Future f
inis...events.py:418>) created at C:\Python\Python380\lib\asyncio\tasks.py:881>
Thanks in advance for your help and time.
Have a good day, evening, afternoon :)
The error message "TypeError: The response value returned by the view function cannot be None" is indicating that the view function (in this case, the update_by_id function) is not returning a value.
It seems that the function update_record does not return anything. If you want to return the string "updated" after updating the record, you should use a return statement like this:
async def update_record(self, data):
# update code here
return 'updated'
And on the update_by_id function you should call the return value of await update_record(input_data) to return it.
async def update_by_id():
input_data = request.get_json()
result = await update_record(input_data)
return result
Another point is that in the second example, you are not returning anything either, you should add a return statement before the end of the function.
Also, you are returning 'ApplicationTopicSchema(many=True).dump(data)' but the input data data is not being defined in the function, you should use the 'result' variable returned by update_record function instead.
async def update_by_id():
input_data = request.get_json()
result = await update_record(input_data)
return ApplicationTopicSchema(many=True).dump(result)
It's important to note that in the first example, the update_record function seems to be missing the self parameter, and could be causing some issues with the class.
It's also important to check if the fetch_one function from super() is waiting for the query with await keyword, and also if the fetch_one is returning something, otherwise it could be the cause of the None return value.
My understanding and knowledge is limited, but I hope this helps. Feel free to shoot me any further questions.

Deformat text in discord.py

I want to remove the formatting from text in discord.py - adding \ before *'s, ```'s etc. I have not yet been able to come up with a perfect solution.
Can anyone tell me what I could use?
I use discord.py and python 3
If this is in a command you can use commands.clean_content
#bot.command()
async def test(ctx, arg: commands.clean_content(fix_channel_mentions=False, use_nicknames=True, escape_markdown=True, remove_markdown=False)):
await ctx.send(arg)
All params are kwarg only and optional, for more info see the docs
If you want to escape markdown for some other text (e.g. from an API), you can use utils.escape_markdown
import discord
text = "Hello my name is **Wasi**"
print(discord.utils.escape_markdown(text))
# 'Hello my name is \*\*Wasi\*\*'
There is also utils.escape_mentions for removing mentions
Discord.py provides a utility function: discord.utils.escape_markdown
This converts:
#```python
#print("hello")
#```
#**bold** *italics*
into
#\`\`\`python
#print("hello")
#\`\`\`
#\*\*bold\*\* \*italics\*

Discord.py: How do I get the user name from the user ID

Yeah, so I got the user ID of the Users, but I'm unable to find code to get the user name, like I tried everything like client.fetch_user(payload.user_id) and client.get_user(user_id) but it won't work.
Here is the code:
#client.command(pass_context = True)
async def test(ctx,id):
print(getname(id))
def getname(a):
return client.get_user(a).name
thanks.
If you're trying to have have it in a different function then you can do:
async def getname(ctx):
user = await ctx.author.guild.fetch_member(id)
return user
If you're trying to get the name specifically try adding .name behind ctx.author.guild.fetch_member(id)
Maybe this is the answer you're looking for?

"Run until complete" loop does not end after function is complete?

I have been working on a Discord bot that pulls information from Ubisoft's Rainbow Six Siege stats API. I am new to coding and I know it's a bit of a bodge, but to retrieve stats I am using some sample code I found in the API's documentation:
#types.coroutine
def run():
auth = api.Auth("my_email", "my_password")
player = yield from auth.get_player(username, api.Platforms.UPLAY)
operator = yield from player.get_operator(oprtr)
print(operator.kills)
global result
result = (operator.kills)
asyncio.get_event_loop().run_until_complete(run())
print (result)
I placed this inside of a command function I created:
#client.command()
async def wins(ctx, username, oprtr):
print (username, oprtr)
Which, together, gives the code below, which I have annotated to show how the loop doesn't end. On its own (without being inside a command), the #types.coroutine works fine, it is just when it is inside of #client.command() that the loop doesn't end.
#client.command()
async def wins(ctx, username, oprtr):
print (username, oprtr)
#types.coroutine
def run():
auth = api.Auth("my_email", "my_password")
player = yield from auth.get_player(username, api.Platforms.UPLAY)
operator = yield from player.get_operator(oprtr)
print(operator.kills) #this value prints, so the function definitely works.
global result
result = (operator.kills)
asyncio.get_event_loop().run_until_complete(run()) #this is the loop which seems to never end,
#and blocks anything from progressing
print (result) #these two outputs do not send, which tells me that everything is being
await ctx.send("Hello") #blocked by the loop
As I said, I'm a fairly new and pretty rubbish coder so I appreciate any help, this has been bugging me all day! If you need any more information I will do my best to give you it.
Instead of using a ruin until complete loop, maybe try looping until a certain variable is true or false.
notdone = true
while notdone == true:
#do whatever in here and when you want it to finish, just set notdone to false.

How to remove or change the default help command?

How do you remove or at least change the format of the default help command in discord.py?
I think changing the format would be nice, I don't really like the format at all.
Try this:
bot.remove_command('help')
Put this at the top of your code, after your imports.
Then create your own.
Or to format it check this out: Click here!
The proper way to disable the help command according to the docs is to pass help_command=None into the constructor for discord.ext.commands.Bot, such as:
bot = commands.Bot(help_command=None)
or
class MyBot(commands.Bot):
def __init__(self):
super().__init__(help_command=None)
This also allows you the opportunity to pass your own help function into the help_command argument for different formatting.
You will need to remove the command for example
client.remove_command('help')
you will need to put it under
client = commands.Bot
it will be like
client = commands.Bot(command_prefix = 'somethingelse')
client.remove_command('help')
Here you can use this:
intents = discord.Intents.all()
activity = discord.Game(name=f"!help in {len(client.guilds)} servers!")
client = commands.Bot(command_prefix="!", intents=intents, activity=activity, status=discord.Status.do_not_disturb, help_command=None)
This is how you should do it so that it preserves the behavior of the help command while letting you change how it looks:
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command```
See the documentation: https://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#help-commands for more details.
For migrating from old helpformatters: https://discordpy.readthedocs.io/en/rewrite/migrating.html#helpformatter-and-help-command-changes
You don't really need to remove the command... It isn't good, using the (prefix)help commandname <- It wont appear then... If you want it embed you can do.
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
client.help_command = NewHelpName()```
The built in help command is of great use

Categories

Resources