Ive been having trouble with this for a little while now. When declaring a async function like:
async def init(loop):
and then I call the function it returns a:
NameError: name 'init' is not defined
Here is how the code all looks:
class Server:
def __init__(self, port):
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
server = loop.run_until_complete(init(loop))
print("Serving on {}".format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
print("\rclosing the server")
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
async def init(loop):
server = await loop.create_server(handle_request, '127.0.0.1', 8881)
return server
async def handle_request():
Any direction that you could point me in would be helpful.
Thanks!
Seems like def init() is inside your class. Move it out of the class by unindenting it:
class Server:
def __init__(self, port):
#....
loop.close()
# IT SHOULD NOT BE HERE
#IT SHOULD BE HERE!!!
async def init(loop):
server = await loop.create_server(handle_request, '127.0.0.1', 8881)
return server
Related
I am working on building an asyncio.Future integration with my Tornado app so I can request a callback. Essentially, I instantiated a class within a class, this creates a future and adds a callback to the function.
However, when I call this I get a bunch of error messages:
Traceback (most recent call last):
File "/Users/robot/tornado/venv/lib/python3.8/site-packages/tornado/web.py", line 1713, in _execute
result = await result
File "pending/request_seven.py", line 31, in get
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
File "pending/request_seven.py", line 25, in _future
fut = self.create_future()
AttributeError: '_asyncio.Future' object has no attribute 'create_future'
Here is what I have tried with my script:
define('port', default = 9057, help="run port 9060", type=int)
class requestFour(tornado.web.RequestHandler):
class scheduleFuture(asyncio.SelectorEventLoop):
#staticmethod
def unwrapper(fut: asyncio.Future, function):
return function()
def _future(self, fun1 ):
fut = self.create_future()
fut.add_done_callback(func(self.unwrapper, function=fun1))
return fut
async def get(self):
client = tornado.httpclient.AsyncHTTPClient()
await self.scheduleFuture._future(client.fetch('https://books.toscrape.com'), self.on_response)
def on_response(self, response):
body = response.body
self.write(body)
self.finish()
def my_app():
app = tornado.web.Application(handlers = [(r'/', requestFour)])
http_server = tornado.httpserver.HTTPServer(app)
return http_server
async def main():
app = my_app()
app.listen(options.port)
shutdown_event = asyncio.Event()
await shutdown_event.wait()
if __name__ == '__main__':
asyncio.run(main())
I want help because I don't want my help command with no categories
code:
class Base64(dccmds.Cog):
#bot.command(pass_context=True)
async def b64encode(ctx, string):
string_b = string.encode("utf-8")
await ctx.send(b64.b64encode(string_b).decode("utf-8"))
#bot.command()
async def b64decode(ctx, string):
string_b = string.encode("utf-8")
await ctx.send(b64.decodebytes(string_b).decode())
bot.add_cog(Base64())
I am getting this error:
I tried everything I could, but still getting the same error
As the error suggests, you're registering the command twice. First, you add it with bot.command(), and then you add it a second time in the cog, causing the error.
The command should be added only once:
class Base64(commands.Cog):
#commands.command() # this does not add the command, so it gets added later when you add the cog
async def b64encode(self, ctx, string):
string_b = string.encode("utf-8")
await ctx.send(b64.b64encode(string_b).decode("utf-8"))
#commands.command()
async def b64decode(self, ctx, string):
string_b = string.encode("utf-8")
await ctx.send(b64.decodebytes(string_b).decode())
client.add_cog(Base64())
I've been grokking some of my sample async code and I'm struggling to understand the flow of the data and how often I find myself awaiting.
Am I using await correctly? Also - are my output types correct? I'd imagine some these should be outputting coroutines (but my Pyright/Pylance type hinting keeps telling me that's wrong...)
The functions that require inspection are governed requests, send, governed_send, and governed_sendall. Maybe I'm not understanding what await is doing completely - and how this interacts with function scopes.
The code works correctly; I'd like to understand why and whether I can optimize out some of these awaits or if that's unnecessary.
import time
import asyncio
import httpx
from typing import Any, Callable, Coroutine, Dict, List
from rich import print
class GovernedClient:
def __init__(self):
self.client = httpx.AsyncClient()
self.loop = asyncio.get_event_loop()
self.semaphore = asyncio.BoundedSemaphore(4)
def __del__(self) -> None:
# Define a destructor that closes the client and the loop.
async def close(self: GovernedClient) -> None:
# An async function is required to await aclose
await self.client.aclose()
self.loop.run_until_complete(close(self))
self.loop.close()
def govern_requests(fn: Callable) -> Callable:
# govern_requests applies semaphore locking to a given callable.
async def call(self, *args, **kwargs):
async with self.semaphore:
return await fn(self, *args, **kwargs)
return call
async def send(self, method: str, url: str) -> httpx.Response:
# A single send.
request = httpx.Request(method, url, headers={'accept': 'application/json'})
return await self.client.send(request)
#govern_requests
async def governed_send(self, method: str, url: str) -> httpx.Response:
# Applies semaphore locking via decorator.
return await self.send(method, url)
def governed_sendall(self, urls: List[str]) -> List[httpx.Response]:
async def goverened_sendall(urls: List[str]) -> List[httpx.Response]:
start = time.time()
awaitables = [self.governed_send('GET', url) for url in urls]
responses = []
for response in asyncio.as_completed(awaitables):
responses.append(await response)
print('Total time: ', int(1000 * (time.time() - start)))
return responses
return self.loop.run_until_complete(goverened_sendall(urls))
if __name__ == '__main__':
URL = 'https://www.icanhazdadjoke.com'
bc = GovernedClient()
urls = [URL for url in range(20)]
responses = bc.governed_sendall(urls)
for response in responses:
print(response.json())
You know that async is a function that will not block the code. Right?
You know that await is an async function caller that when called it will not block the code. Right?
So There's no using too much async/await because if you using it it will not blocking your code unlike def and functioname().
I guess you may understand.
Happy day!
import discord
from discord.ext import commands
class GetRole(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command(name = '역할')
async def GetRoles(self, ctx):
m = await ctx.send(':one: 을 눌러 <#&817598594009661450> 역할을 얻으세요.\n:two: 를 눌러 <#&817978024700018719> 역할을 얻으세요.\n:three: 를 눌러 <#&817978098531172362> 역할을 얻으세요.')
await m.add_reaction('1️⃣')
#commands.Cog.listener()
async def on_raw_reaction_add(self, ctx, payload: discord.RawReactionActionEvent):
user = self.bot.get_user(payload.id)
if user.bot:
return
if str(payload.reaction.emoji) == "1️⃣":
role = self.bot.get_role(817598594009661450)
await user.add_roles(role)
await user.send('DONE!')
def setup(bot):
bot.add_cog(GetRole(bot))
yeah. i tried it, but error has occured
TypeError: on_raw_reaction_add() missing 1 required positional argument: 'payload'
How I fix this error?
The raw_reaction_add event does not receive both a Context and a RawReactionActionEvent object; only the payload is given, so your listener should only have two arguments in it which is self, and payload.
I've been trying to figure this out forever now, but it seems that my discord.py command prefix for my bot does not work. Currently, here is my code:
players = {}
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
await client.change_presence(activity=discord.Game(name="with your words!"))
called_once_an_hour.start()
#client.command()
async def test():
await client.send('test')
#client.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
#client.command(pass_context = True)
async def leave(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
await voice_client.disconnect()
#client.command(pass_context = True)
async def play(ctx):
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = await voice_client.create_ytdl_player('https://www.youtube.com/watch?v=YMw-9mXfccY')
players[server.id] = player
player.start()
print(f"Playing Are you winning son in server voice client: {voice_client}")
First client command was mainly for debugging purposes, but its just never called out.
I also think I already have all the necessary imports
Your test command needs to look like:
async def test(ctx):
await ctx.send('test')
I can run this successfully with !test
The context is passed by default, pass_context = True is no longer necessary.
See the commands docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html