用 Python 编写 Discord 机器人 - 如何让机器人运行得更快?

时间:2021-01-28 21:38:15

标签: python discord.py

我注意到每当触发命令时,机器人通常需要几秒钟的时间来响应。有什么办法可以提高机器人的整体速度?我是编程新手,所以任何见解都将不胜感激。如果有帮助,这是我的代码:

import discord
import os
import random
import praw
from keep_alive import keep_alive
from discord.ext import commands
from discord.ext.commands import Bot
import time


client = commands.Bot(command_prefix='.')


sec_triggers = ['just a sec', 'Just a sec', 'just a second', 'Just a second', 'one sec', 'one second', 'One sec', 'One second']
monke_triggers = ['monke', 'Monke', 'Monkey', 'monkey']
hello_triggers = ['hello there', 'Hello there', 'hello There', 'Hello There']
f_triggers = ['f in the chat', 'F in the chat', 'f in the Chat', 'F in the Chat']
colors = [0xff0000, 0xff3300, 0xff6600, 0xff9900, 0xffcc00, 0xffff00, 0xccff00, 0x99ff00, 0x66ff00, 0x33ff00, 0x00ff00, 0x00ff33, 0x00ff66, 0x00ff99, 0x00ffcc, 0x00ffff, 0x00ccff, 0x0099ff, 0x0066ff, 0x0033ff, 0x0000ff, 0x3300ff, 0x6600ff, 0x9900ff, 0xcc00ff, 0xff00ff, 0xff00cc, 0xff0099, 0xff0066, 0xff0033]
client.remove_command('help')

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

  await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you, Wazowski. Always Watching. Always."))



@client.event
async def on_message(message):
  if message.author == client.user:
   return
  
  msg = message.content
  
  if any(word in msg for word in monke_triggers):
   await message.channel.send(file=discord.File('Reject Humanity, Return to Monke.jpg'))
  
  if any(word in msg for word in sec_triggers):
   time. sleep(1)
   await message.channel.send("It's been one second")
  
  if any(word in msg for word in hello_triggers):
    await message.channel.send(file=discord.File('General_Kenobi.gif'))
  
  if any(word in msg for word in f_triggers):
    mention = message.author.name
    await message.channel.send(f"{mention} had paid their respects.")

  if message.content.lower() == 'f' or message.content.lower() == 'F':
    mention = message.author.name
    await message.channel.send(f"{mention} had paid their respects.")
  
  await client.process_commands(message)


@client.command()
async def catjam(ctx, *, text):
    message = f"{text}"
    new_message = ""
    for char in message:
      new_message += f"<a:catjam:800476635655962644>{char}"
    new_message += "<a:catjam:800476635655962644>"
    await ctx.send(new_message)
    await ctx.message.delete()

@client.command()
async def echo(ctx, *, text):
  await ctx.send(f"{text}")
  await ctx.message.delete()

@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, text):
    reason = f"{text}"
    mention = ctx.message.author.name
    pfp = member.avatar_url
    em = discord.Embed(title = f"{member} has been kicked.", color = random.choice(colors))
    em.add_field(name="Reason:", value=reason)
    em.add_field(name="Responsible User:", value=mention)
    em.set_thumbnail(url=(pfp))
    await member.kick(reason=reason)
    await ctx.send(embed=em)

@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, text):
    reason = f"{text}"
    mention = ctx.message.author.name
    pfp = member.avatar_url
    em = discord.Embed(title = f"{member} has been banned.", description= f"__Reason:__ {reason} __Responsible moderator:__ {mention}", color = random.choice(colors))
    em.set_thumbnail(url=(pfp))
    await member.ban(reason=reason)
    await ctx.send(embed=em)


@client.command()
async def comic(ctx):
    subreddit = reddit.subreddit("comic")
    all_subs = []
    hot = subreddit.hot(limit = 100)

    for submission in hot:
      all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    em = discord.Embed(title = name, color = random.choice(colors))

    em.set_image(url = url)
    await ctx.send(embed = em)

@client.command()
async def joke(ctx):
    subreddit = reddit.subreddit("cleanjokes")
    all_subs = []
    hot = subreddit.hot(limit = 100)

    for submission in hot:
      all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    text = random_sub.selftext
    em = discord.Embed(title = name, color = random.choice(colors), description = text)

    await ctx.send(embed = em)


@client.command()
async def meme(ctx):
    subreddit = reddit.subreddit("cleanmemes")
    all_subs = []
    hot = subreddit.hot(limit = 100)

    for submission in hot:
       all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    em = discord.Embed(title = name, color = random.choice(colors))

    em.set_image(url = url)
    await ctx.send(embed = em)

@client.command()
async def cat(ctx):
    subreddit = reddit.subreddit("catpictures")
    all_subs = []
    hot = subreddit.hot(limit = 100)

    for submission in hot:
       all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    em = discord.Embed(title = name, color = random.choice(colors))

    em.set_image(url = url)
    await ctx.send(embed = em)

@client.command()
async def dog(ctx):
    subreddit = reddit.subreddit("dogpictures")
    all_subs = []
    hot = subreddit.hot(limit = 100)

    for submission in hot:
       all_subs.append(submission)
  
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    em = discord.Embed(title = name, color = random.choice(colors))

    em.set_image(url = url)
    await ctx.send(embed = em)

@client.command()
async def help(ctx):
  em = discord.Embed(color = random.choice(colors))
  em.add_field(name='General Commands', value='__help__- Displays this message', inline=True)
  await ctx.send(embed = em)


@client.command()
async def server(ctx):
  server = ctx.message.guild

  roles = str(len(server.roles))
  emojis = str(len(server.emojis))
  channels = str(len(server.channels))

  embeded = discord.Embed(title=server.name, description='Server Info', color=random.choice(colors))
  embeded.set_thumbnail(url=server.icon_url)
  embeded.add_field(name="Created on:", value=server.created_at.strftime('%d %B %Y at %H:%M UTC+3'), inline=False)
  embeded.add_field(name="Server ID:", value=server.id, inline=False)
  embeded.add_field(name="Users on server:", value=server.member_count, inline=True)
  embeded.add_field(name="Server owner:", value=server.owner, inline=True)


  embeded.add_field(name="Server Region:", value=server.region, inline=True)
  embeded.add_field(name="Verification Level:", value=server.verification_level, inline=True)

  embeded.add_field(name="Role Count:", value=roles, inline=True)
  embeded.add_field(name="Emoji Count:", value=emojis, inline=True)
  embeded.add_field(name="Channel Count:", value=channels, inline=True)

  await ctx.send(embed=embeded) 


keep_alive()

client.run(os.getenv('TOKEN'))

(我在这里添加这部分是因为它不会让我修改问题。它告诉我“看起来你的帖子主要是代码,请添加更多细节”。这就是我正在做的,你不需要阅读这部分。)

2 个答案:

答案 0 :(得分:2)

这在很大程度上取决于多种因素。

  1. 你的代码 - 如果没有看到你的代码,我无法帮助你,但无论如何 - 几秒钟就很多了,更好的代码不会真正在小范围内改变它
  2. 您的硬件 - 此外,这只是机器人性能的一小部分,但应该可以忽略不计
  3. (我认为)这是您的互联网连接。或者 Discord 的 API 现在有问题。

当然,还有更多因素,但很可能是您的互联网连接。

答案 1 :(得分:2)

如果您在本地托管您的机器人,那么我非常确定这是您的互联网。我给你举个例子。

我在本地托管时的 Websocket 延迟: enter image description here

使用 Heroku 托管时的 Websocket 延迟: enter image description here

我在本地托管时也遇到响应迟缓的情况,而使用 Heroku 则几乎是即时响应。

有些命令可能需要比一般命令更长的时间(例如将图像上传到 Imgur 的 aiohttp get/post 会话,当我在本地托管时大约需要 5 秒,但当我使用 Heroku 运行时几乎立即出现)