How to connect with multiply websockets using Jupyter notebook - websocket

This program on Jupyter notebook connect only with first websocket. What is wrong?
session1 = aiohttp.ClientSession()
session2 = aiohttp.ClientSession()
async with session1.ws_connect('host1') as ws1:
async for msg1 in ws1:
print(msg1.data)
await asyncio.sleep(5)
async with session2.ws_connect('host2') as ws2:
async for msg2 in ws2:
print(msg2.data)
await asyncio.sleep(5)

import asyncio
import aiohttp
urls = [host1, host2, ...]
async def websocket(url):
session = aiohttp.ClientSession()
async with session.ws_connect(url) as ws:
async for msg in ws:
print(msg.data)
loop = asyncio.get_event_loop()
tasks = [websocket(url) for url in urls]
loop.run_until_complete(asyncio.wait(tasks))

Related

How to creat a slash command in cog

I created a slash command under message cog to clean up messages, but it shows that 'the application is not responding' in discord
Here is my code:
class Message(InitCog):
# clean messages
#app_commands.command(name='clean', description='clean messages')
#app_commands.describe(num='number of message')
#commands.has_permissions(manage_channels=True)
async def clean(self, ctx, *, num: int):
await ctx.channel.purge(limit=num)
await discord.Interaction.response.defer(ephemeral=True)
await discord.Interaction.followup.send(f'deleted {num} messages')
async def setup(client):
await client.add_cog(Message(client))
and main code:
import asyncio
import discord
import os
from discord.ext import commands
client = commands.Bot(command_prefix='?', intents=discord.Intents.all())
async def setup_hook():
for Filename in os.listdir('./cmds'):
if Filename.endswith('.py'):
await client.load_extension(f'cmds.{Filename\[:-3\]}')
#client.event
async def on_ready():
sync = await client.tree.sync()
print(f"bot logged as {client.user}")
print(f'synced {len(sync)} commands')
async def main():
await setup_hook()
await client.start(jdata\['Token'\])
if __name__ == "__main__":
asyncio.run(main())
Already solved , Use interaction.channel.purge instead of ctx.channel.purge
#app_commands.command(name='clean', description='clean messages')
#app_commands.describe(num='number of message')
#commands.has_permissions(manage_channels=True)
async def clean(self, interaction: discord.Interaction, num: int):
try:
await interaction.channel.purge(limit=num)
await interaction.response.defer()
await interaction.followup.send(f'deleted {num} messages')
except Exception as e:
print(e)

What is the reason for the error in the int class in the code I've written?

What is causing the error in the init class?
I'm trying to declare a class, but I'm not sure what to do.
(It is discord.ext)
my code is:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
#Client = command_prefix
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
#client.command()
async def ping(ctx):
await ctx.send('pong')
async def on_message(message):
#commands.Bot(name="<<kick", pass_context= True)
#commands.has_permissions(administrator=True)
async def _kick(ctx, *, username: discord.Member, reason=None):
await user_name.kick(reason=reason)
await ctx.send(str(user_name) + '\n```User was kick!```')
client.run(token)
error is
TypeError: __init__() missing 1 required positional argument: 'command_prefix'
Thanks for reading.
You have
#commands.Bot(name="<<kick", pass_context= True) which should be #client.command(name="kick", pass_context= True) you also had an indent error (async def on_message(message):) which usually comes at the end of your commands. await ctx.send(str(user_name) + '\n```User was kick!```') here you refer to user_name instead of username, which you defined in the function.
I tested the code and this is what it should look like when fixed:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
token = "XXXXXXXXXXXXXXXX"
# Client = command_prefix
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
#client.command()
async def ping(ctx):
await ctx.send('pong')
#client.command(name="kick", pass_context=True)
#commands.has_permissions(administrator=True)
async def _kick(ctx, *, username: discord.Member, reason=None):
await username.kick(reason=reason)
await ctx.send(str(username) + '\n```User was kick!```')
client.run(token)

Using an async function in another function

I'm trying to understand how to use an async function inside another function:
I'm trying to send messages via Telegram whenever something happens during my code.
Telegram logger:
from telethon import TelegramClient, sync
import asyncio
async def msgtelegram(entity, msg,api_id=xxx, api_hash='xx'):
client = TelegramClient('Session', api_id, api_hash)
await client.start()
if not await client.is_user_authorized():
await client.sign_in('xxx')
await client.send_message(entity, msg)
await client.disconnect()
def func():
try:
print('hello!')
except:
await msgtelegram(entity, msg)
Calling await msgtelegram() outside of a function seems to work correctly.
Am I missing something or am I using async wrong?
Thank you!
you could use either asyncio.run() or loop.run_until_complete() so for your example it would be
from telethon import TelegramClient, sync
import asyncio
async def msgtelegram(entity, msg,api_id=xxx, api_hash='xx'):
client = TelegramClient('Session', api_id, api_hash)
await client.start()
if not await client.is_user_authorized():
await client.sign_in('xxx')
await client.send_message(entity, msg)
await client.disconnect()
def func():
try:
print('hello!')
except:
asyncio.run(msgtelegram(entity, msg))

How to use await in schedule library?

I got this exception7 How to fix it?
RuntimeWarning: coroutine 'job' was never awaited
self._run_job(job)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
from aiogram import Dispatcher, Bot, executor
from aiogram.types import Message,CallbackQuery
from asyncio import sleep
import schedule
bot = Bot(token)
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def start(message : Message):
await bot.send_message(message.chat.id, message.text)
async def job():
await bot.send_message(626420006, 'job done!')
async def scheduler():
schedule.every(2).seconds.do(lambda : job())
while True:
schedule.run_pending()
await sleep(1)
if __name__ == "__main__":
dp.loop.create_task(scheduler())
executor.start_polling(dp,skip_updates=True)
I used another library aioschedule
from aiogram import Dispatcher, Bot, executor
from aiogram.types import Message,CallbackQuery
import asyncio
import time
import aioschedule as schedule
bot = Bot('')
dp = Dispatcher(bot)
#dp.message_handler(commands=['start'])
async def start(message : Message):
await bot.send_message(message.chat.id, message.text)
async def job():
print('hello')
await bot.send_message(626420006, 'job done!')
async def scheduler():
schedule.every(1).seconds.do(job)
# loop = asyncio.get_event_loop()
while True:
await schedule.run_pending()
await asyncio.sleep(2)
if __name__ == "__main__":
dp.loop.create_task(scheduler())
executor.start_polling(dp,skip_updates=True)

aiohttp websocket and redis pub/sub

i created a simple websocket server using aiohttp . my server reads message from redis pub/sub and sends it to client .
this is my websocket code:
import aiohttp
from aiohttp import web
import aioredis
router = web.RouteTableDef()
#router.get("/ws")
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
sub = request.config_dict["REDIS"]
ch, *_ = await sub.subscribe('hi')
async for msg in ch.iter(encoding='utf-8'):
await ws.send_str('{}: {}'.format(ch.name, msg))
async def init_redis(app):
redis_pool = await aioredis.create_redis_pool('redis://localhost')
app["REDIS"] = redis_pool
yield
redis_pool.close()
await redis_pool.wait_closed()
async def init_app():
app = web.Application()
app.add_routes(router)
app.cleanup_ctx.append(init_redis)
return app
web.run_app(init_app())
my first client can connect to server and receive messages but when i create another client to connect to this endpoint it receive no messages !
what is the problem ? how can i fix this problem?
You need to call create_redis for each client and publish the message to the channel. Otherwise, only the first client will receive the subscribed message.
So, you can edit your code as follows.
import aiohttp
from aiohttp import web
import aioredis
import asyncio
router = web.RouteTableDef()
async def reader(ws, ch):
while (await ch.wait_message()):
await ws.send_str('{}: {}'.format(ch.name, msg))
#router.get("/ws")
async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
sub = await aioredis.create_redis_pool('redis://localhost')
pub = await aioredis.create_redis_pool('redis://localhost')
ch, *_ = await sub.subscribe('hi')
asyncio.ensure_future(reader(ws, ch))
async for msg in ws:
await pub.publish('hi', msg)
sub.close()
pub.close()
async def init_app():
app = web.Application()
app.add_routes(router)
return app
web.run_app(init_app())
Please note there may be minor syntax error (e.g. format of the message), but this is the structure that you should follow as it worked for me. I got it to work with my application.

Resources