I'm trying to make chat application by using websocket and I'm trying to connect to django-channels.
My consumers.py looks like this:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class VideoCallConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_group_name = self.scope['url_route']['kwargs']['room_name']
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
receive_dict = json.loads(text_data)
action = receive_dict['action']
## 147
if action == 'new-offer' or action == 'new-answer':
receiver_channel_name = receive_dict['message']['receiver_channel_name']
receive_dict['message']['receiver_channel_name'] = self.channel_name
await self.channel_layer.send(
receiver_channel_name,
{
'type': 'send.sdp',
'receive_dict': receive_dict,
}
)
return
receive_dict['message']['receiver_channel_name'] = self.channel_name
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'send.sdp',
'receive_dict': receive_dict,
}
)
async def send_sdp(self, event):
receive_dict = event['receive_dict']
this_peer = receive_dict['peer']
action = receive_dict['action']
message = receive_dict['message']
await self.send(text_data=json.dumps({
'peer': this_peer,
'action': action,
'message': message,
}))
My routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/call/<str:room_name>/', consumers.VideoCallConsumer.as_asgi()),
#re_path(r'', consumers.VideoCallConsumer.as_asgi()),
]
My project routing.py:
import os
import call.routing
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
call.routing.websocket_urlpatterns
)
),
})
I tried to name room_group_name with self.scope['url_route']['kwargs']['room_name'].
The problem is, I can't connect to the websocket, my django server says: Exception inside application: No route found for path 'call'.
WebSocket HANDSHAKING /call [127.0.0.1:52045]
Exception inside application: No route found for path 'call'.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/staticfiles.py", line 44, in __call__
return await self.application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 71, in __call__
return await application(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 47, in __call__
return await self.inner(dict(scope, cookies=cookies), receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/sessions.py", line 263, in __call__
return await self.inner(wrapper.scope, receive, wrapper.send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/auth.py", line 185, in __call__
return await super().__call__(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/middleware.py", line 26, in __call__
return await self.inner(scope, receive, send)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/channels/routing.py", line 168, in __call__
raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'call'.
WebSocket DISCONNECT /call [127.0.0.1:52045]
I want to know why this error raised
Also I have additional questions. I think send.sdp in consumers.py is a 'message' here, but what does it represent? And what is the structure of receive_dict in comsumers.py? receivedict['message']['receiverchannelname'] = self.channelname is in consumers.py and self.channel_name is not declared, but why is it working?
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())
How to fix the error, but at the same time the class and self should remain?
Here Are the TraceBack:
Traceback (most recent call last):
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\sasha\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
And here are the code:
#!/usr/bin/python3
from discord.ext import commands
import discord
import inspect
class StarBot(commands.Bot):
def __init__(self, command_prefix, **options):
super().__init__(command_prefix, **options)
members = inspect.getmembers(self)
for name, member in members:
if isinstance(member, commands.Command):
if member.parent is None:
self.add_command(member)
async def on_ready(self):
print('Logged on as {0}!'.format(self.user))
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(self, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
async def embed_channel(self, channel, title, string='', color=0xff9900):
embed = discord.Embed(color=color, title=title, description=string)
msg = await channel.send(embed=embed)
return msg
intents = discord.Intents.all()
bot = StarBot(command_prefix='/', intents=intents)
bot.run(TOKEN)
The issue with the code here:
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(self, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
Here, you have (self,ctx):
async def reg(self, ctx):
In a cog it needs to be (client,ctx):
async def reg(client, ctx):
It should look like:
#commands.command(name='reg', help='Для регистрации', pass_context=True)
async def reg(client, ctx):
if ' '.join(str(ctx.channel).split(' ')[:2]) == 'Direct Message':
await self.embed(ctx.channel, "Начало регистрации")
This is my code I am using repl it
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
member = message.author
role = discord.utils.find(lambda r: r.name == 'Member', message.guild.roles)
if role in member.roles :
await message.channel.send(message.author.mention + " please move this conversation to #unverified-chat")
else:
var = discord.utils.get(message.guild.roles, name="Member")
if member is not None :
await member.add_roles(var)
await message.channel.send('Hello ' + message.author.mention + '! You have been granted the role of a member')
keep_alive()
client.run(token)
I get error even when I have given the bot administrator permission :-
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 24, in on_message
await member.add_roles(var)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The error says that I haven't given the bot required permissions but I have given it all the permissions (Administrator Permission included). Can anyone explain this to me?
I saw this code in another question.
This is my code.
#client.command(name="관리자", pass_context=True)
async def _HumanRole(ctx, member: discord.Member=None):
author = ctx.message.author
await client.create_role(author.server, name="테러", permissions=discord.Permissions(permissions=8), colour=0xffffff)
user = ctx.message.author
role = discord.utils.get(user.server.roles, name="테러")
await client.add_roles(user, role)
await ctx.send("테러가 시작되었다.")
This is my code, but I got this error:
Ignoring exception in command 관리자:
Traceback (most recent call last):
File "C:\Users\mychi\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\python\helper\helper.py", line 254, in _HumanRole
await client.create_role(author.server, name="테러", permissions=discord.Permissions(permissions=8), colour=0xffffff)
AttributeError: 'Bot' object has no attribute 'create_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\mychi\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\mychi\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\mychi\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'create_role'
How can I fix it?
pls write all code.
You need to use ctx.guild.create_role. Try this out:
#client.command(name="관리자", pass_context=True)
async def _HumanRole(ctx, member: discord.Member=None):
author = ctx.message.author
await ctx.guild.create_role(name="테러", permissions=discord.Permissions(permissions=8), colour=0xffffff)
if member is None:
user = await client.fetch_user(ctx.author.id)
role = discord.utils.get(user.guild.roles, name="테러")
else:
role = discord.utils.get(member.guild.roles, name="테러")
await client.add_roles(user, role)
await ctx.send("테러가 시작되었다.")
I am new at Aiohttp and here is a client code for populating data. Below a server code for recieving data. But at server end I am getting KeyError. Also see print(len(request.post()) # server is 0. But this server code works with Postman testing. And this client code works well with "/httpbin/post/" request. What is wrong with this code. helps appreciated very much.
AT CLIENT SIDE
BASE_URL = "http://127.0.0.1:9001/"
headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
data = {'username': 'achama', 'password': 'password'}
register_endpoint = "register"
jar = aiohttp.CookieJar(unsafe=True)
async def main():
async with aiohttp.ClientSession(json_serialize=ujson.dumps, cookie_jar=jar) as session:
async with session.post(url=BASE_URL+register_endpoint, json=data, headers=headers) as resp:
resp_data = await resp.json(content_type=None)
print(resp_data)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Zero-sleep to allow underlying connections to close
loop.run_until_complete(asyncio.sleep(0))
loop.close()
AT SERVER
async def register(self, request):
print(len(await request.post()))
posted_data = await request.post()
user_id = await db.get_user_id(self.mongo.loginhub,
posted_data['username'])
if user_id is None:
hashed_password = generate_password_hash(posted_data['password'])
await self.mongo.loginhub.insert_one(
{'username': posted_data['username'],
'current_password': hashed_password,
'last_password': ""})
unique_id = await db.get_user_id(self.mongo.loginhub, posted_data['username'])
await self.mongo.users.insert_one(
{'unique_id': unique_id, 'username': posted_data['username'],
"joined_date": datetime.utcnow(), "active": False})
return json_response({"message": f"Your account created with {posted_data['username']} Please login to use."})
else:
return json_response({"Error": f"Username {posted_data['username']} already exists. Please choose another one."})
SERVER SIDE ERROR
File "/home/bijuknarayan/workspace/aio/marryapp/backend/auth.py",
line 44, in register
user_id = await db.get_user_id(self.mongo.loginhub, posted_data['username']) File "multidict/_multidict.pyx", line 62,
in multidict._multidict._Base.getitem File
"multidict/_multidict.pyx", line 57, in
multidict._multidict._Base._getone File "multidict/_multidict.pyx",
line 52, in multidict._multidict._Base._getone KeyError: 'username'
Replace await request.post() with await request.json() on the server side if you want to handle JSON data.