I built a Discord bot and added it to my server using Python code. The bot is supposed to create a CSV file with all server members when I run a specific command.
I’m confused about the actual usage part. When I’m chatting in the Discord server where my bot is active, what exactly do I need to type to trigger the bot’s functionality? I can see the bot is online but I don’t know the correct way to call the command that will make it generate and send me the member list.
Here’s my bot code:
"""Bot for exporting server member data"""
import csv
import time
from discord.ext import commands
from discord.ext.commands import Bot
# settings
COMMAND_PREFIX = "!"
BOT_TOKEN = "your_token_here"
client = Bot(command_prefix=COMMAND_PREFIX)
@client.event
async def on_ready():
print('Bot is online')
print(client.user.name)
print(client.user.id)
print('------')
@client.event
async def on_command_error(err, context):
if isinstance(err, commands.CommandNotFound):
return
else:
print(err)
@client.command(pass_context=True)
async def members(context):
"""Generates CSV with all server members"""
await client.request_offline_members(context.message.server)
start_time = time.time()
user_names = [member.display_name for member in context.message.server.members]
with open('output.csv', mode='w', encoding='utf-8', newline='') as file:
csv_writer = csv.writer(file, dialect='excel')
for name in user_names:
csv_writer.writerow([name])
end_time = time.time()
await client.send_file(context.message.author, 'output.csv', filename='members.csv',
content="CSV file ready! Check your DMs. Created in {:.4}ms.".format((end_time - start_time)*1000))
if __name__ == '__main__':
client.run(BOT_TOKEN)