Running multiple bots in 1 script without warning - python

Goals
Running multiple bot in the same time with same command
What I've tried
I've coded and searching through internet I found this. I know it's the answer but if I created client1 and client2. Here in my code I just make 1 client (client1)
token1 = getenv("TOKEN1")
token2 = getenv("TOKEN2")
intents = discord.Intents().all()
client1 = commands.Bot(command_prefix = '.', intents = intents)
slash = SlashCommand(client1, sync_commands=True)
client1.remove_command('help')
#client1.event
async def on_ready():
await client1.change_presence(activity=discord.Game(name='Bot Ready'))
print("logged in")
for filename in listdir('cogs'):
if filename.endswith('.py'):
client1.load_extension(f'cogs.{filename[:-3]}')
def meFunction(ctx):
return ctx.author.id == 385053392059236353
loop = asyncio.get_event_loop()
loop.create_task(client1.start(token1))
loop.create_task(client1.start(token2))
loop.run_forever()
And then this warning message appear in my command prompt
client_session: <aiohttp.client.ClientSession object at 0x00000247DB381BE0>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x00000247DB370D60>, 2262.609)]']
connector: <aiohttp.connector.TCPConnector object at 0x00000247DB38E280>
Task exception was never retrieved
future: <Task finished name='Task-5' coro=<Client.start() done, defined at C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py:649> exception=RuntimeError('Concurrent call to receive() is not allowed')>
Traceback (most recent call last):
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 566, in connect
await self.ws.poll_event()
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\gateway.py", line 555, in poll_event
msg = await self.socket.receive(timeout=self._max_heartbeat_timeout)
File "C:\Users\chris\AppData\Local\Programs\Python\Python39\lib\site-packages\aiohttp\client_ws.py", line 216, in receive
raise RuntimeError("Concurrent call to receive() is not allowed")
RuntimeError: Concurrent call to receive() is not allowed
Last solution what I know is making client2 which is copy of client1

Related

Use pycord to make a music bot

My English is not good, I am still a newcomer, please forgive me if the question is not good.
I'm using PyCord 2.3.2 to make a discord music robot. Currently, I only do the join command. Although I can join the channel, it throws an error.
Ignoring exception in command join:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\Desktop\BOT\Cogs\Music.py", line 52, in join
await channel.connect()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1932, in connect
await voice.connect(timeout=timeout, reconnect=reconnect)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\voice_client.py", line 404, in connect
self.ws = await self.connect_websocket()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\voice_client.py", line 375, in connect_websocket
await ws.poll_event()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 944, in poll_event
await self.received_message(utils._from_json(msg.data))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 861, in received_message
await self.initial_connection(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 898, in initial_connection
recv = await self.loop.sock_recv(state.socket, 70)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 696, in sock_recv
return await self._proactor.recv(sock, n)
RuntimeError: Task <Task pending name='pycord: on_message' coro=<Client._run_event() running at C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:377>> got Future <_OverlappedFuture pending overlapped=<pending, 0x183de095fc0>> attached to a different loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Task <Task pending name='pycord: on_message' coro=<Client._run_event() running at C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:377>> got Future <_OverlappedFuture pending overlapped=<pending, 0x183de095fc0>> attached to a different loop
I tried to find the problem according to the error, but there is no good solution, hope to find a solution here.
this is my program
Cogs:
import discord
from discord.ext import commands,tasks
import os
import youtube_dl
import asyncio
from definition.Classes import Cog_Extension
class Music(Cog_Extension):
#commands.command(name='join', help='Tells the bot to join the voice channel')
async def join(self,ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
def setup(bot):
bot.add_cog(Music(bot))
Bot:
import discord
import asyncio
from discord.ext import commands
import os
import json
with open("config.json" , "r" ,encoding="utf8") as configFiles:
config = json.load(configFiles)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=config["command_prefix"], intents=intents)
#bot.event
async def on_ready():
os.system('clear')
print("-"*15)
print("🌐bot online")
print("-"*15)
print(bot.user.name)
print(bot.user.id)
print(bot.user)
print("-"*15)
Activity = discord.Activity(type=discord.ActivityType.watching,name="bot")
await bot.change_presence(activity=Activity)
await asyncio.sleep(3)
async def load():
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
async def main():
await load()
await bot.start(config["Token"])
asyncio.run(main())
I think you could simplify your code a bit and that'll likely help:
def load():
# doesn't need to be async
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
load()
bot.run(config["Token"])
Or, if you really want to use bot.start then the docs recommend doing it this way:
def load():
# still doesn't need to be async
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
load()
# for python3.11
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# loop = asyncio.get_event_loop()
try:
loop.run_until_complete(bot.start(config["Token"]))
except KeyboardInterrupt:
loop.run_until_complete(close())
# cancel all tasks lingering
finally:
loop.close()
I used the latter method, and copied your cog and my bot joined the VC I was in without any issues.

How to get User object from id discord.py

I have a bot that sends dm pings to a user whos Id is given as a parameter in a command.
This is the command:.spam ID #_OF_PINGS
I run into the following error:
Ignoring exception in command spam:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 16, in spam
await ctx.send(f'Started pinging {user.name} {num} times.')
AttributeError: 'NoneType' object has no attribute 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.6/site-packages/discord/ext/commands/core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.6/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: 'NoneType' object has no attribute 'name'
Here is my code:
from discord.ext import commands
token = 'MyBotTokenHere'
prefix = '.'
client = commands.Bot(command_prefix=prefix)
client.remove_command("help")
#client.event
async def on_ready():
print('Ready')
#client.command()
async def spam(ctx, id1: int, num: int):
user = client.get_user(id1)
await ctx.send(f'Started pinging {user.name} {num} times.')
for i in range(num):
await user.send(f'<#{str(id1)}>')
await ctx.send(f'Finished {num} pings for {user.name}')
client.run(token)
It was working fine yesterday, but today, it broke down for some reason.
How do I fix it?
P.S. I hosted it on Heroku
You can use a converter for this:
#client.command()
async def spam(ctx, user: discord.User, num: int):
await ctx.send(f'Started pinging {user.name} {num} times.')
for i in range(num):
await user.send(f'<#{str(id1)}>')
await ctx.send(f'Finished {num} pings for {user.name}')
This way, Discord will automatically try to get the discord.User instance that corresponds to the id that you pass as an argument, and you can also #mention someone if you want to & it'll still work.
Also, starting from Discord 1.5.0, you now need to pass in intents when initializing a bot, which you clearly aren't doing yet. Update your Discord, and use the following to initialize your bot:
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=prefix, intents=intents)
More info on the how's and why's of intents in the relevant API documentation. You'll also want to enable members on your bot's Privileged Intents page, which is explained in the linked API docs as well.

Why does calling asyncio.sleep causes websocket connection to close?

I am trying to build a websockets server where the client connects and sends a request of some kind, and then the server adds that request to a queue and returns something back when finished.
to simulate the process of queueing and waiting for tasks to finish, I called asyncio.sleep whenever the process is supposed to be called.
however, whenever I do that I get the following error from the client-side:
Traceback (most recent call last):
File "D:/Python/server/client1.py", line 10, in <module>
asyncio.get_event_loop().run_until_complete(message())
File "C:\ProgramData\Anaconda3\envs\server\lib\asyncio\base_events.py", line 587, in run_until_complete
return future.result()
File "D:/Python/server/client1.py", line 8, in message
print(await socket.recv())
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 509, in recv
await self.ensure_open()
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 812, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
and this error from the server-side:
Task exception was never retrieved
future: <Task finished coro=<queue_dispatcher() done, defined at D:/RamNew2020/Python/server/asyncserver.py:39> exception=ConnectionClosedOK('code = 1000 (OK), no reason')>
Traceback (most recent call last):
File "D:/Python/server/asyncserver.py", line 45, in queue_dispatcher
await data_from_q.sendto_websocket("yay")
File "D:/Python/server/asyncserver.py", line 20, in sendto_websocket
await self.mywebsocket.send(message)
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 555, in send
await self.ensure_open()
File "C:\ProgramData\Anaconda3\envs\server\lib\site-packages\websockets\protocol.py", line 803, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), no reason
My scripts:
server.py:
import asyncio
import websockets
import datetime
import random
queue = asyncio.Queue()
async def rnd_sleep(t):
# sleep for T seconds on average
await asyncio.sleep(t * random.random() * 2)
#When a client sends a message the information is saved in a Request object,
#including the socket connection
class Request:
def __init__(self, mywebsocket, mydat):
self.mywebsocket = mywebsocket
self.mydat = mydat
self.start_time_of_request = datetime.datetime.now()
self.id = random.randint(0, 128)
async def sendto_websocket(self, message):
await self.mywebsocket.send(message)
def get_dat(self):
return self.mydat
def get_start_time(self):
return self.start_time_of_request
async def add_to_queue(websocket, path):
global queue
dat = await websocket.recv()
base64dat = Request(websocket, dat)
await queue.put(base64dat)
#problem in queue_dispatcher
async def queue_dispatcher(q):
while True:
data_from_q = await q.get()
print(data_from_q.id)
await asyncio.sleep(1) #The problem is here, whenever I remove it, it works
await data_from_q.sendto_websocket("yay")
q.task_done()
async def main():
global queue
asyncio.create_task(queue_dispatcher(queue))
pass
start_server = websockets.serve(add_to_queue, 'localhost', 5000)
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
client.py:
import asyncio
async def message():
async with websockets.connect("ws://localhost:5000")as socket:
msg = input("What do you want to send: ")
await socket.send(msg)
print(await socket.recv())
asyncio.get_event_loop().run_until_complete(message())
In addition, whenever I try to await any other async function, it works fine no matter how long.

Can`t send DM message (Discord bot )

I need to send a private message to the user with help Discord bot.
Using Django + Python.
file path > discordbot(django app)/management/commands/trades.py
i.e I run python manage.py trades
class Command(BaseCommand):
def handle(self, *args, **options):
client = Bot(description="LivePage", command_prefix="-", pm_help = False)
async def send_order():
await client.wait_until_ready()
counter = 0
while not client.is_closed:
user = discord.Object(id = '415618634120167424') # i get my id with using command in the discord client - \# + nickname
await client.send_message(user, 'milkiii')
await asyncio.sleep(5) # task runs every 60 seconds
#client.event
async def on_ready():
print('Use this link to invite {}:'.format(client.user.name))
client.loop.create_task(send_order())
client.run()
But when a script will running I have next message:
Task exception was never retrieved
future: <Task finished coro=<Command.handle.<locals>.send_order() done, defined at /home/worksection/worksection/botdiscord/management/commands/trades.py:24> exception=NotFound('NOT FOUND (status code: 404): Unknown Channel',)>
Traceback (most recent call last):
File "/home/worksection/worksection/botdiscord/management/commands/trades.py", line 41, in send_order
await client.send_message(user, 'milkiii')
File "/home/worksection/env/lib/python3.6/site-packages/discord/client.py", line 1152, in send_message
data = yield from self.http.send_message(channel_id, content, guild_id=guild_id, tts=tts, embed=embed)
File "/home/worksection/env/lib/python3.6/site-packages/discord/http.py", line 198, in request
raise NotFound(r, data)
discord.errors.NotFound: NOT FOUND (status code: 404): Unknown Channel
If I change await client.send_message(user, 'milkiii') to > await client.send_message(415618634120167424, 'milkiii')
I will see next error :
Task exception was never retrieved
future: <Task finished coro=<Command.handle.<locals>.send_order() done, defined at /home/worksec
/worksection/botdiscord/management/commands/trades.py:24> exception=InvalidArgument('Destination
t be Channel, PrivateChannel, User, or Object. Received int',)>
Traceback (most recent call last):
File "/home/worksection/worksection/botdiscord/management/commands/trades.py", line 41, in sen
der
await client.send_message(415618634120167424, 'milkiii')
File "/home/worksection/env/lib/python3.6/site-packages/discord/client.py", line 1145, in send
sage
channel_id, guild_id = yield from self._resolve_destination(destination)
File "/home/worksection/env/lib/python3.6/site-packages/discord/client.py", line 289, in _reso
destination
raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Re
ed int
Can you help me? :<

Trying to make a Discord bot with discord.py, getting errors

I'm trying to get the bot to send a message every few seconds from a set of predefined messages.
import discord
import asyncio
import random
client = discord.Client()
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("channel id here")
messages = ["Hello!", "How are you doing?", "Howdy!"]
await client.send_message(channel, random.choice(messages))
await asyncio.sleep(120)
client.loop.create_task(background_loop())
client.run("discord token here")
But when i try too run it, i get this error in the console and no messages are sent into the chat.
/usr/bin/python3.5 /root/PycharmProjects/untitled/Loop.py
Task exception was never retrieved
future: <Task finished coro=<background_loop() done, defined at /root/PycharmProjects/untitled/Loop.py:8> exception=InvalidArgument('Destination must be Channel, PrivateChannel, User, or Object. Received NoneType',)>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/root/PycharmProjects/untitled/Loop.py", line 13, in background_loop
await client.send_message(channel, random.choice(messages))
File "/usr/local/lib/python3.5/dist-packages/discord/client.py", line 1145, in send_message
channel_id, guild_id = yield from self._resolve_destination(destination)
File "/usr/local/lib/python3.5/dist-packages/discord/client.py", line 289, in _resolve_destination
raise InvalidArgument(fmt.format(destination))
discord.errors.InvalidArgument: Destination must be Channel, PrivateChannel, User, or Object. Received NoneType
I fixed this by writing a helper function to get the Channel object from the client
def get_channel(channels, channel_name):
for channel in client.get_all_channels():
print(channel)
if channel.name == channel_name:
return channel
return None
client = discord.Client()
general_channel = get_channel(client.get_all_channels(), 'general')
await client.send_message(general_channel, 'test msg')

Categories

Resources