我正在尝试为接受用户输入 (steam64id) 的机器人创建一个 /whitelist 命令,并将其添加到 mongoDB 数据库,并在所有 whitelist.txt 文件中添加 steam64id
但是我使用的代码出现错误
这是我试过的命令
import discord
from discord.ext import commands
import urllib.request
import os
import valve.source.a2s
import valve.source.master_server
import valve.steam.api
from main import client
from key import steamAPIKey
from key import MongoDB
import pymongo
# MongoDB setup
mongo_client = pymongo.MongoClient(MongoDB)
mongo_db = mongo_client['SilentDB']
mongo_collection = mongo_db['whitelist']
#Getting folder list
VipServerFolderList = os.listdir('./VIP')
print(VipServerFolderList)
VipServerFolderList.remove('.steam')
VipServerFolderList.remove('nohup.out')
print(VipServerFolderList)
#Total score - For later ;)
totalscore = 0
class Whitelist(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print('Whitelist system is ready!')
@commands.command()
@commands.has_role('Premium Drivers | T1', 'Top Tier Patreon Supporter', 'Patreon Supporter', 'Admin', 'Moderator')
async def addwhitelist(self, ctx, steam64id):
server_folders = VipServerFolderList # replace with your server's folder name
whitelist_file = f'{VipServerFolderList}/whitelist.txt'
Invalid64ID = discord.Embed(
colour=None,
color=None,
title="Failed to whiteliste on VIP Servers",
url=None
)
Invalid64ID.set_footer(text="-HSCU Devs")
Invalid64ID.set_thumbnail(url="https://cdn3.emoji.gg/emojis/x.png")
#embed.set_image(url="https://i.imgur.com/lk76B9l.png")
Invalid64ID.add_field(name='Result:', value=f"An error occured or {steam64id} is not a valid ID, please try again!", inline=False)
whitelistedSuccesfully = discord.Embed(
colour=None,
color=None,
title="Sucesfully whitelisted on VIP Servers!",
url=None
)
whitelistedSuccesfully.set_footer(text="-HSCU Devs")
whitelistedSuccesfully.set_thumbnail(url="https://i.imgur.com/k7ht8Du.png")
#embed.set_image(url="https://i.imgur.com/lk76B9l.png")
whitelistedSuccesfully.add_field(name='Result:', value=f'Steam ID {steam64id} added to whitelist for {server_folders}.', inline=False)
Alreadywhitelisted = discord.Embed(
colour=None,
color=None,
title="You are already whitelisted on VIP Servers!",
url=None
)
Alreadywhitelisted.set_footer(text="-HSCU Devs")
Alreadywhitelisted.set_thumbnail(url="https://i.imgur.com/k7ht8Du.png")
#embed.set_image(url="https://i.imgur.com/lk76B9l.png")
Alreadywhitelisted.add_field(name='Result:', value="You have been succesfully whitelisted", inline=False)
try:
api = valve.steam.api.SteamAPI(steamAPIKey) # replace with your Steam API key
profile = api.get_player_summary(steam64id)
if profile is None:
await ctx.send(embed=Invalid64ID)
except:
await ctx.send(embed=Invalid64ID)
else:
# Add to database
try:
mongo_collection.insert_one({'discord_id': str(ctx.author.id), 'steam_id': steam64id, 'total_score': totalscore})
except:
await ctx.send('Error adding to database')
return
with open(whitelist_file, 'r') as f:
if steam64id in f.read():
await ctx.send(embed=Alreadywhitelisted)
else:
with open(whitelist_file, 'a') as f:
f.write(f'{steam64id}\n')
await ctx.send(embed=whitelistedSuccesfully)
@client.event
async def on_member_update(before, after):
# Check if user was removed from role
role = discord.utils.get(after.guild.roles, name='Premium Drivers | T1')
if role in before.roles and role not in after.roles:
# Remove from database
try:
mongo_collection.delete_one({'discord_id': str(after.id)})
except:
pass
steam64id = mongo_collection.find_one({'steam_id': str(after.id)})
# Update whitelist.txt files
for server_folder in VipServerFolderList:
whitelist_file = f'{server_folder}/whitelist.txt'
try:
with open(whitelist_file, 'r') as f:
lines = f.readlines()
with open(whitelist_file, 'w') as f:
for line in lines:
if line.strip() != steam64id:
f.write(line)
except:
return
async def setup(client):
await client.add_cog(Whitelist(client))
以及它返回的错误
Traceback (most recent call last):
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "e:\AC Server\Plugins\HscuDiscordBot\cogs\Whitelist.py", line 5, in <module>
import valve.source.a2s
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\site-packages\valve\source\a2s.py", line 10, in <module>
from . import messages
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\site-packages\valve\source\messages.py", line 379, in <module>
class Message(collections.Mapping):
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'collections' has no attribute 'Mapping'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "e:\AC Server\Plugins\HscuDiscordBot\main.py", line 29, in <module>
asyncio.run(starter())
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "e:\AC Server\Plugins\HscuDiscordBot\main.py", line 25, in starter
await load()
File "e:\AC Server\Plugins\HscuDiscordBot\main.py", line 20, in load
await client.load_extension(f"cogs.{filename[:-3]}")
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Kayce\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Whitelist' raised an error: AttributeError: module 'collections' has no attribute 'Mapping'
我不太确定是什么原因造成的