我从 Python 开始,目前正在使用 API 开发 Discord 机器人。到目前为止一切顺利,一切正常。现在,我希望在没有控制台的服务器上托管脚本,这意味着我希望输出进入文件而不是控制台。我目前有以下工作:
import discord
import logging
logging.basicConfig(filename='.\output.log', filemode='w', level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s')
xzbot = discord.Client()
# logging when the bot starts
@xzbot.event
async def on_ready():
logging.info('Logged in as ' + xzbot.user.name + ' (' + xzbot.user.id + ')\n')
Run Code Online (Sandbox Code Playgroud)
所以这段代码会将所有警告和信息放入output.log中。话虽如此,它不适用于 Discord.py 引发的异常,例如当机器人尝试在没有权限的情况下发送消息时“权限被拒绝”。
Discord API 中有一个内置函数可以处理这个问题:
discord.on_error(event, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
所以我可以这样调用这个函数:
async def xzbot.on_error(event, *args, **kwargs):
pass
Run Code Online (Sandbox Code Playgroud)
现在,我尝试使用event,*args或者做一些事情,**kwargs但我需要一些帮助才能以我可以使用 的格式获得它logging.warning()。我所能得到的只是objecta 的结果print(*args),而且我不知道如何正确格式化它。
我刚刚发现这个网站,我想知道是否有人可以帮助我。我真的不知道这个标题是否合适,但暂时就这样吧。
所以,我有一个如下所示的代码:
@client.command(pass_context=True)
async def member(self, *, member: discord.Member = None, role : discord.Role = None):
if member is None:
await client.say("You need to tag someone!")
elif role is None:
await client.say("You need to tag a role to add!")
else:
await client.add_roles(member, role)
await client.say("Role added!")
Run Code Online (Sandbox Code Playgroud)
我认为它“工作”得很好,因为在输入 !member @Dude 命令时我没有看到任何错误。BOT 只是告诉我需要标记要添加的角色。但!当我标记要添加的角色时,它不起作用。事实上,问题在于,BOT认为角色I标记是成员名称的一部分。也许有了错误会更好。 我告诉你的错误是该图像的最后一行。
正如您所看到的,它表示未找到该成员。但第二个 ID 应该是该角色的 ID。我究竟做错了什么?我对不和谐.py 真的很不好,所以如果有人可以帮助我,他会非常好!:)
(另外,抱歉我的英语不好,如果这是题外话,我也很抱歉,只是我厌倦了这些错误,因为当一个错误解决后,我总是会得到另一个错误。)
编辑:我刚刚修复了这个问题,但现在我收到了 perms 错误。“禁止:禁止(状态代码:403):缺少权限”
是否可以使用机器人更改不和谐服务器所有者的昵称?
更新。我有电子服务器。我想给我的机器人更改我昵称的权利。我可以这样做吗?
I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something simple, but I would appreciate the help.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
TOKEN = '<token-here>'
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
@bot.event
async def on_message(message):
if message.content …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个 Web 应用程序来管理我的 Discord 服务器的用户。在我的数据库中,我只存储了用户的 ID。代码在浏览器中运行。但我也添加了 node.js 标签,因为我现在不知道即使通过调用在 node.js 中编程的服务器函数也能做到
我曾尝试使用 discord.js API,但据我所知,它需要一个不和谐的机器人来做到这一点。那不是我想要的。我想从我的前端检索用户的信息,即使是通过调用后端函数,但没有始终在线的不和谐机器人。换句话说,我需要更简单的东西。
我想仅使用 id 来请求用户的信息。在 javascript 中执行此操作的最佳方法是什么?
我想要达到的目标:
我想在外部程序执行 console_app.exe 时在 Discord 频道上发送消息,所以我决定使用纯休息:
我通过 https://discord.com/developers/applications
我有 ClientId 和 ClientSecret,现在我想从代码登录并在特定频道上发送消息
我正在获取令牌而没有响应问题,例如:
{
"access_token": "6qrZcUqja781...HBFG",
"token_type": "Bearer",
"expires_in": 604800,
"scope": "identify connections"
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试发送消息(函数WriteMessage)时,我Unauthorized出于某种原因
整个代码:
private static readonly RestClient client = new RestClient("https://discord.com");
public string Perform()
{
client.Authenticator = new HttpBasicAuthenticator(_config.ClientId, _config.ClientSecret);
var token = GetToken();
client.Authenticator = null;
return WriteMessage(token);
}
Run Code Online (Sandbox Code Playgroud)
private string GetToken()
{
var signInRequest = new RestRequest("/api/v6/oauth2/token", Method.POST);
signInRequest.AddHeader("content-type", "application/x-www-form-urlencoded");
signInRequest.AddParameter("grant_type", "client_credentials");
signInRequest.AddParameter("scope", "identify connections");
var result = client.Execute<AuthResult>(signInRequest);
return result.Data.access_token; …Run Code Online (Sandbox Code Playgroud) 您好,所以我已经尝试解决这个问题几个小时了,但无法弄清楚出了什么问题,我之前在 discord python 中进行了 api 调用,但这是第一次使用这样的多个变量。
@client.command()
async def random(ctx):
url = ('https://randomuser.me/api/')
response = requests.get(url)
title = response.json()["title"]
first = response.json()["first"]
last = response.json()["last"]
number = response.json()["number"]
street = response.json()["name"]
city = response.json()["city"]
state = response.json()["state"]
postcode = response.json()["postcode"]
country = response.json()["country"]
phone = response.json()["phone"]
age = response.json()["age"]
dob = response.json()["date"]
gender = response.json()["gender"]
username = response.json()["username"]
password = response.json()["password"]
image = response.json()['large']
embed = discord.Embed(title="Random Generator", description="**Name:** f'{title}, {first} {last}\n**Address:** {number} {street}, {city}, {state}, {postcode}, {country}\n**Phone:** {phone}\n**Age:** {age}, …Run Code Online (Sandbox Code Playgroud) @commands.command()
async def emojify(self, ctx, *, text):
emojis = []
for s in text.lower():
if s.isdecimal():
num2emo = {'0':'zero', '1':'one', '2':'two',
'3':'three', '4':'four', '5':'five',
'6':'six', '7':'seven', '8':'eight',
'9':'nine'}
emojis.append(f':{num2emo.get(s)}:')
elif s.isalpha():
emojis.append(f':regional_indicator_{s}:')
else:
emojis.append(s)
await ctx.send(''.join(emojis))
Run Code Online (Sandbox Code Playgroud)
此命令将单词转换为不和谐的表情符号(例如 dank memer emojify)
我如何让它在发送之前检查消息字符长度有多长,以便它可以打印错误或继续?
有可能做这样的事情吗?根据我的理解,您应该使用,if (enabled == true)但我不确定如何使用。
我收到以下错误:
Traceback (most recent call last):
File "main.py", line 41, in <module>
@bot.event()
TypeError: event() missing 1 required positional argument: 'coro'
Run Code Online (Sandbox Code Playgroud)
我的代码:
主文件
#------importing packages
import keep_alive
import os
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = '-', case_insensitive=True)
my_token = os.environ['Token']
#------When bot is online
@bot.event
async def on_ready():
#status
#playing game status
await bot.change_presence(activity=discord.Game(
name=f'On {len(bot.guilds)} Servers | -help'))
print('Bot is Ready')
@bot.event()
async def on_message(message):
# if message.content.startswith(bot.user.mentioned_in(message)):
# await message.channel.send('My prefix is `-`')
if …Run Code Online (Sandbox Code Playgroud) discord ×10
python ×6
discord.py ×5
bots ×2
javascript ×2
c# ×1
command ×1
discord.js ×1
f-string ×1
node.js ×1
python-3.x ×1