discord.py Invite Tracker - python

When i use a script i found on here, which allowed you to track a users invites another member
to discord. The script works great, for a short while then i get the following error
Task exception was never retrieved
future: exception=AttributeError("'NoneType' object has no attribute 'invites'")>
Traceback (most recent call last):
File "H:/TheVoidv2/bot.py", line 1509, in fetch
invs = await gld.invites()
and this error once the bot has ran for a good few hours
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<fetch() done, defined at C:\Users\Administrator\Desktop\TheVoidv2\bot.py:1416> exception=HTTPException('503 Service Unavailable (error code: 0): upstream connect error or disconnect/reset before headers. reset reason: connection failure')>
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\TheVoidv2\bot.py", line 1423, in fetch
invs = await gld.invites()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\guild.py", line 1407, in invites
data = await self._state.http.invites_from(self.id)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 225, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 503 Service Unavailable (error code: 0): upstream connect error or disconnect/reset before headers. reset reason: connection failure
import datetime
import json
import os
import commands
client = discord.Client()
cfg = open("config.json", "r")
tmpconfig = cfg.read()
cfg.close()
config = json.loads(tmpconfig)
token = config["token"]
guild_id = config["server-id"]
logs_channel = config["logs-channel-id"]
invites = {}
last = ""
async def fetch():
global last
global invites
await client.wait_until_ready()
gld = client.get_guild(int(guild_id))
logs = client.get_channel(int(logs_channel))
while True:
invs = await gld.invites()
tmp = []
for i in invs:
for s in invites:
if s[0] == i.code:
if int(i.uses) > s[1]:
usr = gld.get_member(int(last))
testh = f"{usr.name} **joined**; Invited by **{i.inviter.name}** (**{str(i.uses)}** invites)"
await logs.send(testh)
tmp.append(tuple((i.code, i.uses)))
invites = tmp
await asyncio.sleep(4)
#client.event
async def on_ready():
print("ready!")
await client.change_presence(activity = discord.Activity(name = "joins", type = 2))
#client.event
async def on_member_join(meme):
global last
last = str(meme.id)
client.loop.create_task(fetch())
client.run(token)

Related

client.fetch_channel() returns AttributeError: '_MissingSentinel' object has no attribute 'is_set'

I want to send a message to a specific channel. I get the channel, but when I try to send a message it makes this error:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\Phantom_Shop\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\nikit\PycharmProjects\Phantom_Shop\temporary_classes.py", line 200, in buy_callback
await channel.send("Test")
AttributeError: 'NoneType' object has no attribute 'send'
I am doing this in a separate file(specifically in a button callback in a View)
Here's the part of separate file that is used:
from temporary_bot import client
channel = client.get_channel(channel_id)
await channel.send("Test")
and here's the main file:
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
channel = client.get_channel(***)
#client.event
async def on_ready():
await tree.sync()
print('We have logged in as {0.user} bot'.format(client))
#tree.command(name = "start", description = "Start the bot")
async def first_command(interaction):
view = Menu_View()
view.add_item(url)
keys = data["profiles"]
if f"{interaction.user}" in keys:
print("Account already in database")
else:
data["profiles"][f"{interaction.user}"] = {}
data["profiles"][f"{interaction.user}"]["balance"] = 0
print("This is bullshit")
data["profiles"][f"{interaction.user}"]["spent"] = 0
data["profiles"][f"{interaction.user}"]["bought_product"] = 0
with open("profiles.json", "w") as file:
json.dump(data, file)
menu = make_menu(interaction.user.avatar)
await interaction.response.send_message(embed=menu, view=view)
if __name__ == "__main__":
client.run(TOKEN)
I tried creating the variable in the main file but it made the same error.
I use a number as my channel id and I tried it with other channels, same thing.
You're trying to get the channel before the bot is started. Try setting it in on_ready:
global channel
channel = client.get_channel(1062092063128166571)
Or better just get it in your callback
channel = client.get_channel(1062092063128166571)
await channel.send("Test")
If you want to save it in a global variable, it's better to use constant-like variable with id
CHANNEL_ID = 1062092063128166571
# Somewhere in a callback...
channel = client.get_channel(CHANNEL_ID)
await channel.send("Test")
I just fixed the problem by creating the channel variable in a third file, then editing it in the on_ready function, and finally importing it in the classes file

playlist load take too much time and my bot get disconnected (yt-dl and discord.py)

I have a strange problem with my bot made with discord.py and youtube-dl, when I load a small playlist the bot works perfectly, when instead I load a long playlist, like 100 songs, the bot has to download them all and then start them , I think the time used to download the songs is seen as inactivity and then the bot disconnects, however it does not disconnect from the channel on discord, only code side it disconnects, how can i solve?
This is my join function:
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("Non sei in un canale non so dove andare")
else:
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
self.is_connected = True
This is my play function:
#commands.command()
async def play(self, ctx, url):
if ctx.voice_client is None:
await self.join(ctx)
if self.is_connected:
with youtube_dl.YoutubeDL(self.YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
#print(info)
titleartist = ''
duration = ''
#print("INFO: " + str(info))
if info.get('_type') == 'playlist':
temp_url = ' '
for x in info.get('entries'):
#print("x: " + str(x))
temp_url = x['formats'][0]['url']
if 'title' in x.keys():
titleartist = x['title']
if 'duration' in x.keys():
duration = x['duration']
self.queue.append(temp_url)
self.songsinfo.append([temp_url, titleartist, duration])
if not self.playing:
self.currentsonginfo = self.songsinfo.pop(0)
temp_song = self.queue.pop(0)
vc = ctx.voice_client
source = await discord.FFmpegOpusAudio.from_probe(temp_song, **self.FFMPEG_OPTIONS)
self.playing = True
time.sleep(2)
vc.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.next_song(ctx, vc, temp_url), self.client.loop))
else:
url2 = info['formats'][0]['url']
if 'title' in info.keys():
titleartist = info['title']
if 'duration' in info.keys():
duration = info['duration']
if self.playing:
self.queue.append(url2)
self.songsinfo.append([url2, titleartist, duration])
self.index += 1
if not self.skipped:
await ctx.send("Musica Aggiunta alla Coda")
else:
self.skipped = False
else:
self.currentsonginfo = [url2, titleartist, duration]
vc = ctx.voice_client
source = await discord.FFmpegOpusAudio.from_probe(url2, **self.FFMPEG_OPTIONS)
self.playing = True
time.sleep(2)
vc.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.next_song(ctx, vc, url2), self.client.loop))
This is the error I get:
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Users\Gian\PycharmProjects\provabot\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Gian\PycharmProjects\provabot\mymusic.py", line 72, in play
vc.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.next_song(ctx, vc, temp_url), self.client.loop))
File "C:\Users\Gian\PycharmProjects\provabot\venv\lib\site-packages\discord\voice_client.py", line 555, in play
raise ClientException('Not connected to voice.')
discord.errors.ClientException: Not connected to voice.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Gian\PycharmProjects\provabot\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Gian\PycharmProjects\provabot\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Gian\PycharmProjects\provabot\venv\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: ClientException: Not connected to voice.
the bot has to download them all and then start them
1. Don't download the tracks, stream the raw URL (The argument for the command line is --get-url) (You say you are downloading but the code does not do that it extracts raw URL?)
2. I've noticed that YT-DL seems to be slower now. I use a new library called YT-DLP It is way faster than YT-DL and I am able to parse through an entire playlist of 200 songs in less than 5 seconds. (not downloading them of course.)
3. Instead of parsing a whole playlist and extracting raw URLs all at once, extract just the regular URL then when it's time for that song to play from the queue, extract the raw URL and then, play it.

AttributeError: 'NoneType' object has no attribute 'remove_roles'

So, I'm making a reaction role command and it keeps giving me the same error,I have enabled intents. members, everything I need but still it gives me the same error.I dont know why its giving me this error,maybe its a bug or somethng??. Well I hope I cant get a answer from here it only hope rn >.<.(this is just to fill the "please add more details thing..sefsdfysdhfjawsdygdefshdgf)
The code :
import discord
from discord.ext import commands
import random
from io import BytesIO
import DiscordUtils
from discord.utils import get
import os
import asyncio as asyncio
import aiohttp
import datetime
import json
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix="?",case_insensitive = True)
client.remove_command("help")
#client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(
payload.guild_id).roles, id=x['role_id'])
await payload.member.add_roles(role)
#client.event
async def on_raw_reaction_remove(payload):
guild = client.get_guild(payload.guild_id)
print("Guild checked.")
member = guild.get_member(payload.user_id)
print("Member checked.")
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
print("got the role")
await member.remove_roles(role)
#client.command(aliases = ['rr'])
#commands.has_permissions(administrator=True, manage_roles=True)
async def reactrole(ctx, emoji, role: discord.Role, *, message):
emb = discord.Embed(title = "REACTION ROLE !",description=message,timestamp = datetime.datetime.utcnow(),color = 0xADD8E6)
emb.set_thumbnail(url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQPiUxyDTBu4dkC8f3tBeOzM8b0sEnK_8iLUg&usqp=CAU")
emb.set_footer(icon_url = ctx.author.avatar_url, text = f"reactrole embed created by : {ctx.author.name}")
emb.set_image(url = "https://www.logolynx.com/images/logolynx/f8/f843b4dd5ec5dc4e56a3f5639341516a.png")
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json.load(json_file)
new_react_role = {'role_name': role.name,
'role_id': role.id,
'emoji': emoji,
'message_id': msg.id}
data.append(new_react_role)
with open('reactrole.json', 'w') as f:
json.dump(data, f, indent=4) ```
and heres the error:
Guild checked.
Member checked.
got the role
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\pangh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\pangh\Desktop\Engineer\Engineer.py", line 256, in on_raw_reaction_remove
await member.remove_roles(role)
AttributeError: 'NoneType' object has no attribute 'remove_roles'
The member attribute isn't available in the on_raw_reaction_remove event.
What you can do instead is
Figure out whether to give or remove the role both in on_raw_reaction_add, when a user reacts check if they have the role, if not add if they do then remove the role. Then remove their reaction from the message. This would essentially be a toggle reaction role.
OR
Use the payload.user_id and fetch the member using await fetch_user(user_id).

Python websocket client close connection

websocket_client.py
#!/usr/bin/env python
# WS client example
import asyncio
import websockets
import json
import sys
import os
import time
from aiortc import RTCPeerConnection, RTCSessionDescription
pcs = []
peer_connections = 0
local_username = "epalxeis"
websocket = None
async def open_websocket():
global websocket
uri = "ws://192.168.1.5:8080"
async with websockets.connect(uri) as websocket:
#send username
await websocket.send(json.dumps({"type":"register","username":local_username}))
async for message in websocket:
message = json.loads(message)
if(message["type"]=="create_peer"):
await create_peer(message["username"],websocket)
elif(message["type"]=="offer"):
await receive_offer(message,websocket)
elif(message["type"]=="answer"):
receive_answer(message,websocket)
elif(message["type"]=="unregister"):
unregister(message,websocket)
async def create_peer(username,websocket):
global pcs
global peer_connections
global local_username
pc = RTCPeerConnection()
pc_index = peer_connections
pcs.append([username,pc])
peer_connections = peer_connections+1
'''
add stream (video-audio to pc)
'''
#pc.on("track")
def on_track(track):
'''
play track with PyQt5
'''
offer = await pcs[pc_index].createOffer()
pcs[pc_index][1].setLocalDescription(offer)
data = {"type":"offer","from":local_username,"to":username,"offer":offer}
await websocket.send(json.dumps(data))
async def receive_offer(message,websocket):
global pcs
global peer_connections
global local_username
username = message["username"]
offer = RTCSessionDescription(sdp=message["offer"]["sdp"], type=message["offer"]["type"])
pc = RTCPeerConnection()
pc_index = peer_connections
pcs.append([username,pc])
peer_connections = peer_connections+1
'''
add stream (video-audio to pc)
'''
#pc.on("track")
def on_track(track):
'''
play track with PyQt5
'''
await pcs[pc_index][1].setRemoteDescription(offer)
answer = await pcs[pc_index][1].createAnswer()
await pcs[pc_index][1].setLocalDescription(answer)
answer_json = {"sdp":answer.sdp,"type":"answer"}
data = {"type":"answer","from":local_username,"to":username,"answer":answer_json}
await websocket.send(json.dumps(data))
async def receive_answer(message,websocket):
global pcs
username = message["username"]
answer = message["answer"]
for pc in pcs:
if(pc[0]==username):
pc[1].setRemoteDescription(answer)
async def unregister(message,websocket):
global pcs
global peer_connections
username = message["username"]
index = 0
counter = 0
for pc in pcs:
if(pc[0]==username):
pc[1].close()
'''
PyQt5 manage for closing Output Device
'''
index = counter
break
counter = counter + 1
del pcs[index]
peer_connections = peer_connections-1
asyncio.get_event_loop().run_until_complete(open_websocket())
websocket_server.py
import asyncio
import websockets
import json
import ssl
peers = ()
async def on_open(websocket,path):
async for message in websocket:
message = json.loads(message)
if(message["type"]=="register"):
await register(websocket,message["username"])
elif(message["type"]=="offer"):
await send_offer(websocket,message)
elif(message["type"]=="answer"):
await send_answer(websocket,message)
elif(message["type"]=="candidate"):
await send_candidate(websocket,message)
await unregister(websocket)
async def register(websocket,username):
global peers
print(username+" logged in.")
peers = peers + ((websocket,username),)
for peer in peers:
if peer[0] is not websocket:
await websocket.send(json.dumps({"type": "create_peer","username":peer[1]}))
async def send_offer(websocket,message):
global peers
offer_creator = message["from"]
offer_receiver = message["to"]
offer = message["offer"]
print(offer_creator+" creates and sends offer to "+offer_receiver)
for peer in peers:
if(peer[1]==offer_receiver):
await peer[0].send(json.dumps({"type": "offer","username":offer_creator,"offer":offer}))
async def send_answer(websocket,message):
global peers
answer_creator = message["from"]
answer_receiver = message["to"]
answer = message["answer"]
print(answer_creator+" creates and sends answer to "+answer_receiver)
for peer in peers:
if(peer[1]==answer_receiver):
await peer[0].send(json.dumps({"type": "answer","username":answer_creator,"answer":answer}))
async def send_candidate(websocket,message):
global peers
candidate_creator = message["from"]
candidate_receiver = message["to"]
candidate = message["candidate"]
print(candidate_creator+" send candidate packet to "+candidate_receiver)
for peer in peers:
if(peer[1]==candidate_receiver):
await peer[0].send(json.dumps({"type": "candidate","username":candidate_creator,"candidate":candidate}))
async def unregister(websocket):
global peers
for peer_1 in peers:
if(peer_1[0]==websocket):
username = peer_1[1]
print(username+" logged out.")
for peer_2 in peers:
if(peer_2[0] is not websocket):
await peer_2[0].send(json.dumps({"type": "unregister","username":username}))
peers_list = list(peers)
peers_list.remove((websocket,username))
peers = tuple(peers_list)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(r'C:\xampp\crt\localhost\server.crt',r'C:\xampp\crt\localhost\server.key')
ssl_context = None
start_server = websockets.serve(on_open, "192.168.1.5", 8080, ssl=ssl_context)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
First i run the websocket_server.py (this code is handling the websocket requests)
Second i run the websocket_client.py
After that i saw in the first cmd: epalxeis logged in.
So the connection is correct.
But if i close the second cmd (with the x button or with the ctr-c), i saw this error in the server's cmd:
Error in connection handler
Traceback (most recent call last):
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 453, in finish_recv
return ov.getresult()
OSError: [WinError 64] Το καθορισμένο όνομα δικτύου δεν είναι πια διαθέσιμο
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 827, in transfer_data
message = await self.read_message()
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 895, in read_message
frame = await self.read_data_frame(max_size=self.max_size)
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 971, in read_data_frame
frame = await self.read_frame(max_size)
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 1047, in read_frame
frame = await Frame.read(
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\framing.py", line 105, in read
data = await reader(2)
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\streams.py", line 723, in readexactly
await self._wait_for_data('readexactly')
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\streams.py", line 517, in _wait_for_data
await self._waiter
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 280, in _loop_reading
data = fut.result()
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 808, in _poll
value = callback(transferred, key, ov)
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 457, in finish_recv
raise ConnectionResetError(*exc.args)
ConnectionResetError: [WinError 64] Το καθορισμένο όνομα δικτύου δεν είναι πια διαθέσιμο
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\server.py", line 191, in handler
await self.ws_handler(self, path)
File "websocket_server.py", line 9, in on_open
async for message in websocket:
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 439, in __aiter__
yield await self.recv()
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 509, in recv
await self.ensure_open()
File "C:\Users\Χρήστος\AppData\Local\Programs\Python\Python38\lib\site-packages\websockets\protocol.py", line 803, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason
The proccess don't stop.
How can i resolve the issue?
Thanks in advance,
Chris Pappas
This post helps you.
The reason program couldn't stop is that sub threads continue to run even if main thread catches an exception and stop. Note that asyncio is implemented by thread (I pursued codes). There are two kinds of thread in Python, normal thread and daemon thread. The former continues to run if parent thread dies, the latter stops. asyncio is implemented with the former, therefore such this problem happens.

discord bot autorole -- in _run_event yield from getattr(self, event)(*args, **kwargs)

I am new to Python and have some issues with my Discord Bot which I do not get fixed. The bot should automatically assign roles to users who join the server for the first time. I can set up autorole successfully. But when a user joins the server, the following error message appears in the console.
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "E:/dev/DiscordBot/main.py", line 35, in on_member_join
await client.add_role(member, role)
File "C:\Program Files\Python36\lib\site-packages\discord\client.py", line 296, in __getattr__
raise AttributeError(msg.format(self.__class__, name))
AttributeError: '<class 'discord.client.Client'>' object has no attribute 'add_role'
C:\Program Files\Python36\lib\site-packages\discord\client.py:314: RuntimeWarning: coroutine 'get' was never awaited
pass
main.py
import discord
from discord.ext import commands
import SECRETS
import STATICS
from commands import cmd_autorole
client = discord.Client()
commands = dict(autorole=cmd_autorole)
#client.event
async def on_ready():
print("Bot is ready!")
await client.change_presence(game=discord.Game(name="with humans"))
#client.event
async def on_message(message):
if message.content.startswith(STATICS.PREFIX):
invoke = message.content[len(STATICS.PREFIX):].split(" ")[0]
args = message.content.split(" ")[1:]
if commands.__contains__(invoke):
await commands.get(invoke).ex(args, message, client, invoke)
else:
await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description=("The command `%s` is not valid!" % invoke)))
#client.event
async def on_member_join(member):
# await client.send_message(member, "**Hello %s,**\n\nwelcome on Discord-Server __**%s**__!\nPlease look first at the main channel %s .\n\nHave Fun!" % (member.name, member.server.name, discord.utils.get(member.server.channels, id="532425431526277135").mention))
role = cmd_autorole.get(member.server)
if not role is None:
await client.add_role(member, role)
client.run(SECRETS.TOKEN)
cmd_autorole.py
import os
from os import path
import discord
async def error(content, channel, client):
await client.send_message(channel, embed=discord.Embed(color=discord.Color.red(), description=content))
async def get(server):
f = "SETTINGS/" + server.id + "/autorole"
if path.isfile(f):
with open(f) as f:
return discord.utils.get(server.roles, id=f.read())
else:
return None
async def savefile(id, server):
if not path.isdir("SETTINGS/" + server.id):
os.makedirs("SETTINGS/" + server.id)
with open("SETTINGS/" + server.id + "/autorole", "w") as f:
f.write(id)
f.close()
async def ex(args, message, client, invoke):
print(args)
if len(args) > 0:
rolename = args.__str__()[1:-1].replace(",", "").replace("'", "")
role = discord.utils.get(message.server.roles, name=rolename)
if role is None:
await error("Please enter a valid role existing on this server!", message.channel, client)
else:
try:
await savefile(role.id, message.server)
await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.green(), description=("Autorole has been successfully set up for the Role `% s`." % role.name)))
except Exception:
await error("Something went wrong while saving autorole!", message.channel, client)
raise Exception
In your cmd_autorole.py file, the get() function is asynchronous, but you haven't awaited it in your main file.
You must to write role = await cmd_autorole.get(member.server) instead of role = cmd_autorole.get(member.server).
Instead of using #client.event for the second events try using #client.listenlike this:
#client.listen
async def on_message(message):
if message.content.startswith(STATICS.PREFIX):
invoke = message.content[len(STATICS.PREFIX):].split(" ")[0]
args = message.content.split(" ")[1:]
if commands.__contains__(invoke):
await commands.get(invoke).ex(args, message, client, invoke)
else:
await client.send_message(message.channel, embed=discord.Embed(color=discord.Color.red(), description=("The command `%s` is not valid!" % invoke)))
#client.listen
async def on_member_join(member):
# await client.send_message(member, "**Hello %s,**\n\nwelcome on Discord-Server __**%s**__!\nPlease look first at the main channel %s .\n\nHave Fun!" % (member.name, member.server.name, discord.utils.get(member.server.channels, id="532425431526277135").mention))
role = cmd_autorole.get(member.server)
if not role is None:
await client.add_role(member, role)

Categories