自动响应事件触发器 Discord.py
Auto Response Event Trigger Discord.py
我正在尝试制作一个自动回复器,在键入特定单词时给出随机回复。但它根本不会触发响应。这是我的事件触发器。也许有人能弄清楚里面坏了什么?
@commands.Cog.listener()
async def on_message(self, ctx, *, message):
msg = ctx.message
guild = ctx.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 1",
"swear 3"]
s_responses = [
"response 1",
"response 2",
"response 3"]
joke_list = [
"joke 1",
"joke 2",
"joke 3"]
joke_response = random.choice(joke_list)
j_response = str(f"""```css\n{joke_response}```""")
s_response = str(f"""```css\n{s_responses}```""")
get_help = str("""```css\nI can't help you with this problem!```""")
bot_web = str("""```css\nhttps:\newhorizon-development.netlify.app\```""")
bns_web = str("""```css\nhttps:\www.blandandsoul.com\```""")
if any(content.startswitch("telljoke")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=j_response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(eembed=embed)
if any(content.startswith(word) for word in bad_list):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=s_response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("gethelp")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=get_help, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("botwebsite")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=bot_web, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("bnsweb")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=bns_web, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
如果有帮助,我正在使用 discord.py 重写...
--编辑--
Smoliarick 提供的有效修复。十分感谢你的帮助。将其编辑到主 post 中,供任何想使用它的人使用 =).
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["SWEAR",
"SWEAR",
"SWEAR"]
responses = ["RESPONSE",
"RESPONSE",
"RESPONSE"]
for bad_word in bad_list:
if bad_word in message.content:
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
return
重命名第二个 on_message
函数并在 @commands.Cog.listener()
中添加 name='on_message'
以重命名函数:
class ExampleBot(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 1",
"swear 3"]
responses = [
"response 1",
"response 2",
"response 3"]
# check bad words
for bad_word in bad_list:
if bad_word in message.content:
return
response = random.choice(responses)
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name,
icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
@commands.Cog.listener(name='on_message')
async def on_message_second(self, message):
print("Hello")
def setup(client):
client.add_cog(ExampleBot(client))
setup(client)
试试这个:
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkie"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
for bad_word in bad_list:
if bad_word in message.content:
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
return
好的,这是我目前的情况:
--编辑--
不小心遗漏了 random.choice 部分...
@commands.Cog.listener()
async def on_message(self, message):
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 2",
"swear 3"
]
responses = [
"response 1",
"response 2",
"response 3"
]
if any(content.startswith(word) for word in bad_list):
return
c_response = str(f"""```css\n{responses}```""")
response = random.choice(c_response)
if any(content.startswith(word) for word in bad_list):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
有些笑话对于嵌入来说太大了,所以我将它们更改为一个有效的 madlib 命令,现在原始代码剩下的就是我上面的内容。
但是它仍然没有响应。和我之前遇到的问题差不多。
我是 运行 它来自一个齿轮,这就是为什么我有 self.client
而不是 client
。
这是我的完整代码...这次我不会省略脏话和回复,因为我的 Events.py
文件很大..
import discord
from discord.ext import commands
from discord import Activity, ActivityType
import json
import datetime
import random
from random import randint
epoch = datetime.datetime.utcfromtimestamp(0)
time_diff = round((datetime.datetime.utcnow() - epoch).total_seconds())
def load_counters():
with open('./data/counters.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('./data/counters.json', 'w') as f:
json.dump(counters, f, indent=4)
class Events(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
await self.client.change_presence(activity=Activity(name=f"r?help | in {len(self.client.guilds)} servers", type=ActivityType.playing))
print(" ")
print("License")
print(" ")
print("Copyright (c) Joshua Lewis")
print(" ")
print("Permission is hereby granted, free of charge, to any person obtaining a copy")
print("of this software and associated documentation files (the Software), to deal")
print("in the Software without restriction, including without limitation the rights")
print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
print("copies of the Software, and to permit persons to whom the Software is")
print("furnished to do so, subject to the following conditions:")
print(" ")
print("The above copyright notice and this permission notice shall be included in all")
print("copies or substantial portions of the Software.")
print(" ")
print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
print("SOFTWARE.")
print("Connecting to Discord API")
print("...")
print("......")
print(".........")
print(f"Logged in as : {self.client.user.name}#{self.client.user.discriminator}")
print("Collecting list of connected guilds")
print("...")
print("......")
print(".........")
print("Connected Guilds:")
print(f"{self.client.guilds}")
def check_all_message(check_for, message):
if check_for in message.content:
return True
elif check_for in message.embed:
return True
@commands.Cog.listener()
async def on_message_delete(self, message):
guild = message.author.guild
author = message.author
ch = message.channel
content = message.content
orange = discord.Color.dark_orange()
for channel in guild.channels:
if str(channel.name) == "log":
msg_del = str(f"""```css\n{content}```""")
aut_name = str(f"""```css\n{author.name}```""")
ch_name = str(f"""```css\n{ch.name}```""")
embed = discord.Embed(color=orange, timestamp=message.created_at)
embed.set_author(name="Message Deleted", icon_url=self.client.user.avatar_url)
embed.add_field(name=f"Message", value=msg_del, inline=False)
embed.add_field(name=f"Message Author", value=aut_name, inline=False)
embed.add_field(name=f"Channel", value=ch_name, inline=False)
embed.set_thumbnail(url=author.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
print(f'message: {content} by {author.name} was deleted in {ch.name}')
@commands.Cog.listener()
async def on_member_join(self, ctx, member):
guild = ctx.guild
msg = ctx.message
gold = discord.Color.dark_gold()
user_join = str(f"""```css\n{member.name} has entered {guild.name}.```""")
for channel in guild.channels:
if str(channel.name) == "log":
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="Use Joined", value=user_join, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_image(url=member.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, ctx, member):
guild = ctx.guild
msg = ctx.message
red = discord.Color.dark_red()
for channel in guild.channels:
if str(channel.name) == "log":
user_left = str(f"""```css\n{member.name} has left {guild.name}""")
embed = discord.Embed(color=red, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="User Left", value=user_left, inline=False)
embed.set_image(url=member.avatar_url)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkey"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
if any(content.startswith(word) for word in bad_list):
return
response = random.choice(responses)
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name,
icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, ctx):
guild = ctx.guild
author = ctx.author
content = ctx.content
"""Logs a user's xp to json file for use with the levels and currency system. If no user data is present, new user data is created."""
if content.startswith('B.') is not True:
if guild != None:
F = open("./data/levels.json")
level = json.load(F)
user_time = round((datetime.datetime.utcnow() - epoch).total_seconds())
if str(f"{guild.name}:{guild.id}") not in level:
level[f"{guild.name}:{guild.id}"] = {}
print(f"A log has been created for {guild.name}:{guild.id}")
if str(f"{author.name}:{author.id}") not in level[f"{guild.name}:{guild.id}"]:
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"] = {"level": "1", "xp": "0", "NT": f"0", "multi": f"1", "txp": f"0", "starttime": f"{user_time}"}
print(f"A log entry has been created for {author.name}:{author.id} in {guild.name}:{guild.id}")
if user_time - int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["NT"]) >= 60:
RNum = randint(1, 5)
MP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["multi"])
XP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["xp"]) + (RNum * MP)
TXP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["txp"]) + (RNum * MP)
LVL = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["level"])
if XP >= 20 * LVL ** 2:
XP = XP % (20 * LVL ** 2)
LVL += 1
F1 = open("./data/currency.json")
mon = json.load(F1)
if str(f"{author.name}:{author.id}") not in mon:
mon[f"{author.name}:{author.id}"] = {"money": "0", "hist": "0", "multimon": "1"}
RNum1 = randint(1, 25)
MM = int(mon[f"{author.name}:{author.id}"]["multimon"])
Money = int(mon[f"{author.name}:{author.id}"]["money"]) + round(RNum1 * (LVL + 1) * MM)
HMoney = int(mon[f"{author.name}:{author.id}"]["hist"]) + round(RNum1 * (LVL + 1) * MM)
F1.close()
mon[f"{author.name}:{author.id}"]["money"] = f"{Money}"
mon[f"{author.name}:{author.id}"]["hist"] = f"{HMoney}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"level"] = f"{LVL}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"xp"] = f"{XP}"
with open("./data/currency.json", "w") as F1w:
json.dump(mon, F1w, indent=4)
print(f"{author.name}\nXP: {XP}\nLevel: {LVL}")
XP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["xp"])
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"multi"] = f"{MP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"xp"] = f"{XP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"txp"] = f"{TXP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"NT"] = f"{user_time}"
ttime = (user_time) - round(int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["starttime"]))
F.close()
with open("./data/levels.json", "w") as Fw:
json.dump(level, Fw, indent=4)
anlvl = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["level"])
ttimeday = int(int(ttime) / 86400)
ttimehour = int((int(ttime) % 86400) / 3600)
ttimemin = int(((int(ttime) % 86400) % 3600) / 60)
if ttimeday == int(1):
tday = ""
else:
tday = "s"
if ttimehour == int(1):
thour = ""
else:
thour = "s"
if ttimemin == int(1):
tmin = ""
else:
tmin = "s"
msgtt = f"{ttimeday} day{tday}, {ttimehour} hour{thour}, and {ttimemin} minute{tmin}"
if anlvl in [10, 20, 25, 50, 75, 100, 150, 200, 300]:
print(f"CONGRATS! {author.mention} has made it to level {anlvl} in just {msgtt}!")
def setup(client):
client.add_cog(Events(client))
这是从 bot.py
文件调用齿轮的函数:
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
好的,现在它只是这样做了....
不知道现在发生了什么...
--编辑--
还有错误信息:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\ranma\cogs\Events.py", line 159, in on_message
await message.channel.send(embed=embed)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\abc.py", line 856, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\http.py", line 225, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required
这是我更新后的代码:
import discord
from discord.ext import commands
from discord import Activity, ActivityType
import json
import datetime
import random
epoch = datetime.datetime.utcfromtimestamp(0)
time_diff = round((datetime.datetime.utcnow() - epoch).total_seconds())
def load_counters():
with open('./data/counters.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('./data/counters.json', 'w') as f:
json.dump(counters, f, indent=4)
class Events(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
await self.client.change_presence(activity=Activity(name=f"r?help | in {len(self.client.guilds)} servers", type=ActivityType.playing))
print(" ")
print("License")
print(" ")
print("Copyright (c) Joshua Lewis")
print(" ")
print("Permission is hereby granted, free of charge, to any person obtaining a copy")
print("of this software and associated documentation files (the Software), to deal")
print("in the Software without restriction, including without limitation the rights")
print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
print("copies of the Software, and to permit persons to whom the Software is")
print("furnished to do so, subject to the following conditions:")
print(" ")
print("The above copyright notice and this permission notice shall be included in all")
print("copies or substantial portions of the Software.")
print(" ")
print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
print("SOFTWARE.")
print("Connecting to Discord API")
print("...")
print("......")
print(".........")
print(f"Logged in as : {self.client.user.name}#{self.client.user.discriminator}")
print("Collecting list of connected guilds")
print("...")
print("......")
print(".........")
print("Connected Guilds:")
print(f"{self.client.guilds}")
def check_all_message(check_for, message):
if check_for in message.content:
return True
elif check_for in message.embed:
return True
@commands.Cog.listener()
async def on_message_delete(self, message):
if not message.author.bot:
guild = message.author.guild
author = message.author
ch = message.channel
content = message.content
orange = discord.Color.dark_orange()
for channel in guild.channels:
if str(channel.name) == "log":
msg_del = str(f"""```css\n{content}```""")
aut_name = str(f"""```css\n{author.name}```""")
ch_name = str(f"""```css\n{ch.name}```""")
embed = discord.Embed(color=orange, timestamp=message.created_at)
embed.set_author(name="Message Deleted", icon_url=self.client.user.avatar_url)
embed.add_field(name=f"Message", value=msg_del, inline=False)
embed.add_field(name=f"Message Author", value=aut_name, inline=False)
embed.add_field(name=f"Channel", value=ch_name, inline=False)
embed.set_thumbnail(url=author.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
print(f'message: {content} by {author.name} was deleted in {ch.name}')
@commands.Cog.listener()
async def on_member_join(self, ctx, member):
if not ctx.author.bot:
guild = ctx.guild
msg = ctx.message
gold = discord.Color.dark_gold()
user_join = str(f"""```css\n{member.name} has entered {guild.name}.```""")
for channel in guild.channels:
if str(channel.name) == "log":
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="Use Joined", value=user_join, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_image(url=member.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, ctx, member):
if not ctx.author.bot:
guild = ctx.guild
msg = ctx.message
red = discord.Color.dark_red()
for channel in guild.channels:
if str(channel.name) == "log":
user_left = str(f"""```css\n{member.name} has left {guild.name}""")
embed = discord.Embed(color=red, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="User Left", value=user_left, inline=False)
embed.set_image(url=member.avatar_url)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkie"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
for bad_word in bad_list:
if bad_word in message.content:
return
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
def setup(client):
client.add_cog(Events(client))
每当我 运行 命令时,这个人就会无休止地发送垃圾邮件。
我正在尝试制作一个自动回复器,在键入特定单词时给出随机回复。但它根本不会触发响应。这是我的事件触发器。也许有人能弄清楚里面坏了什么?
@commands.Cog.listener()
async def on_message(self, ctx, *, message):
msg = ctx.message
guild = ctx.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 1",
"swear 3"]
s_responses = [
"response 1",
"response 2",
"response 3"]
joke_list = [
"joke 1",
"joke 2",
"joke 3"]
joke_response = random.choice(joke_list)
j_response = str(f"""```css\n{joke_response}```""")
s_response = str(f"""```css\n{s_responses}```""")
get_help = str("""```css\nI can't help you with this problem!```""")
bot_web = str("""```css\nhttps:\newhorizon-development.netlify.app\```""")
bns_web = str("""```css\nhttps:\www.blandandsoul.com\```""")
if any(content.startswitch("telljoke")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=j_response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(eembed=embed)
if any(content.startswith(word) for word in bad_list):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=s_response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("gethelp")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=get_help, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("botwebsite")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=bot_web, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
if any(content.startswith("bnsweb")):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=bns_web, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await ctx.send(embed=embed)
如果有帮助,我正在使用 discord.py 重写...
--编辑--
Smoliarick 提供的有效修复。十分感谢你的帮助。将其编辑到主 post 中,供任何想使用它的人使用 =).
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["SWEAR",
"SWEAR",
"SWEAR"]
responses = ["RESPONSE",
"RESPONSE",
"RESPONSE"]
for bad_word in bad_list:
if bad_word in message.content:
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
return
重命名第二个 on_message
函数并在 @commands.Cog.listener()
中添加 name='on_message'
以重命名函数:
class ExampleBot(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 1",
"swear 3"]
responses = [
"response 1",
"response 2",
"response 3"]
# check bad words
for bad_word in bad_list:
if bad_word in message.content:
return
response = random.choice(responses)
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name,
icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
@commands.Cog.listener(name='on_message')
async def on_message_second(self, message):
print("Hello")
def setup(client):
client.add_cog(ExampleBot(client))
setup(client)
试试这个:
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkie"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
for bad_word in bad_list:
if bad_word in message.content:
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
return
好的,这是我目前的情况:
--编辑--
不小心遗漏了 random.choice 部分...
@commands.Cog.listener()
async def on_message(self, message):
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = [
"swear 1",
"swear 2",
"swear 3"
]
responses = [
"response 1",
"response 2",
"response 3"
]
if any(content.startswith(word) for word in bad_list):
return
c_response = str(f"""```css\n{responses}```""")
response = random.choice(c_response)
if any(content.startswith(word) for word in bad_list):
return
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
有些笑话对于嵌入来说太大了,所以我将它们更改为一个有效的 madlib 命令,现在原始代码剩下的就是我上面的内容。
但是它仍然没有响应。和我之前遇到的问题差不多。
我是 运行 它来自一个齿轮,这就是为什么我有 self.client
而不是 client
。
这是我的完整代码...这次我不会省略脏话和回复,因为我的 Events.py
文件很大..
import discord
from discord.ext import commands
from discord import Activity, ActivityType
import json
import datetime
import random
from random import randint
epoch = datetime.datetime.utcfromtimestamp(0)
time_diff = round((datetime.datetime.utcnow() - epoch).total_seconds())
def load_counters():
with open('./data/counters.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('./data/counters.json', 'w') as f:
json.dump(counters, f, indent=4)
class Events(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
await self.client.change_presence(activity=Activity(name=f"r?help | in {len(self.client.guilds)} servers", type=ActivityType.playing))
print(" ")
print("License")
print(" ")
print("Copyright (c) Joshua Lewis")
print(" ")
print("Permission is hereby granted, free of charge, to any person obtaining a copy")
print("of this software and associated documentation files (the Software), to deal")
print("in the Software without restriction, including without limitation the rights")
print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
print("copies of the Software, and to permit persons to whom the Software is")
print("furnished to do so, subject to the following conditions:")
print(" ")
print("The above copyright notice and this permission notice shall be included in all")
print("copies or substantial portions of the Software.")
print(" ")
print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
print("SOFTWARE.")
print("Connecting to Discord API")
print("...")
print("......")
print(".........")
print(f"Logged in as : {self.client.user.name}#{self.client.user.discriminator}")
print("Collecting list of connected guilds")
print("...")
print("......")
print(".........")
print("Connected Guilds:")
print(f"{self.client.guilds}")
def check_all_message(check_for, message):
if check_for in message.content:
return True
elif check_for in message.embed:
return True
@commands.Cog.listener()
async def on_message_delete(self, message):
guild = message.author.guild
author = message.author
ch = message.channel
content = message.content
orange = discord.Color.dark_orange()
for channel in guild.channels:
if str(channel.name) == "log":
msg_del = str(f"""```css\n{content}```""")
aut_name = str(f"""```css\n{author.name}```""")
ch_name = str(f"""```css\n{ch.name}```""")
embed = discord.Embed(color=orange, timestamp=message.created_at)
embed.set_author(name="Message Deleted", icon_url=self.client.user.avatar_url)
embed.add_field(name=f"Message", value=msg_del, inline=False)
embed.add_field(name=f"Message Author", value=aut_name, inline=False)
embed.add_field(name=f"Channel", value=ch_name, inline=False)
embed.set_thumbnail(url=author.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
print(f'message: {content} by {author.name} was deleted in {ch.name}')
@commands.Cog.listener()
async def on_member_join(self, ctx, member):
guild = ctx.guild
msg = ctx.message
gold = discord.Color.dark_gold()
user_join = str(f"""```css\n{member.name} has entered {guild.name}.```""")
for channel in guild.channels:
if str(channel.name) == "log":
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="Use Joined", value=user_join, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_image(url=member.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, ctx, member):
guild = ctx.guild
msg = ctx.message
red = discord.Color.dark_red()
for channel in guild.channels:
if str(channel.name) == "log":
user_left = str(f"""```css\n{member.name} has left {guild.name}""")
embed = discord.Embed(color=red, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="User Left", value=user_left, inline=False)
embed.set_image(url=member.avatar_url)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
msg = message
guild = message.guild
content = message.content
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkey"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
if any(content.startswith(word) for word in bad_list):
return
response = random.choice(responses)
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name,
icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=response, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, ctx):
guild = ctx.guild
author = ctx.author
content = ctx.content
"""Logs a user's xp to json file for use with the levels and currency system. If no user data is present, new user data is created."""
if content.startswith('B.') is not True:
if guild != None:
F = open("./data/levels.json")
level = json.load(F)
user_time = round((datetime.datetime.utcnow() - epoch).total_seconds())
if str(f"{guild.name}:{guild.id}") not in level:
level[f"{guild.name}:{guild.id}"] = {}
print(f"A log has been created for {guild.name}:{guild.id}")
if str(f"{author.name}:{author.id}") not in level[f"{guild.name}:{guild.id}"]:
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"] = {"level": "1", "xp": "0", "NT": f"0", "multi": f"1", "txp": f"0", "starttime": f"{user_time}"}
print(f"A log entry has been created for {author.name}:{author.id} in {guild.name}:{guild.id}")
if user_time - int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["NT"]) >= 60:
RNum = randint(1, 5)
MP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["multi"])
XP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["xp"]) + (RNum * MP)
TXP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["txp"]) + (RNum * MP)
LVL = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["level"])
if XP >= 20 * LVL ** 2:
XP = XP % (20 * LVL ** 2)
LVL += 1
F1 = open("./data/currency.json")
mon = json.load(F1)
if str(f"{author.name}:{author.id}") not in mon:
mon[f"{author.name}:{author.id}"] = {"money": "0", "hist": "0", "multimon": "1"}
RNum1 = randint(1, 25)
MM = int(mon[f"{author.name}:{author.id}"]["multimon"])
Money = int(mon[f"{author.name}:{author.id}"]["money"]) + round(RNum1 * (LVL + 1) * MM)
HMoney = int(mon[f"{author.name}:{author.id}"]["hist"]) + round(RNum1 * (LVL + 1) * MM)
F1.close()
mon[f"{author.name}:{author.id}"]["money"] = f"{Money}"
mon[f"{author.name}:{author.id}"]["hist"] = f"{HMoney}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"level"] = f"{LVL}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"xp"] = f"{XP}"
with open("./data/currency.json", "w") as F1w:
json.dump(mon, F1w, indent=4)
print(f"{author.name}\nXP: {XP}\nLevel: {LVL}")
XP = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["xp"])
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"multi"] = f"{MP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"xp"] = f"{XP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"txp"] = f"{TXP}"
level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"][f"NT"] = f"{user_time}"
ttime = (user_time) - round(int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["starttime"]))
F.close()
with open("./data/levels.json", "w") as Fw:
json.dump(level, Fw, indent=4)
anlvl = int(level[f"{guild.name}:{guild.id}"][f"{author.name}:{author.id}"]["level"])
ttimeday = int(int(ttime) / 86400)
ttimehour = int((int(ttime) % 86400) / 3600)
ttimemin = int(((int(ttime) % 86400) % 3600) / 60)
if ttimeday == int(1):
tday = ""
else:
tday = "s"
if ttimehour == int(1):
thour = ""
else:
thour = "s"
if ttimemin == int(1):
tmin = ""
else:
tmin = "s"
msgtt = f"{ttimeday} day{tday}, {ttimehour} hour{thour}, and {ttimemin} minute{tmin}"
if anlvl in [10, 20, 25, 50, 75, 100, 150, 200, 300]:
print(f"CONGRATS! {author.mention} has made it to level {anlvl} in just {msgtt}!")
def setup(client):
client.add_cog(Events(client))
这是从 bot.py
文件调用齿轮的函数:
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
好的,现在它只是这样做了....
不知道现在发生了什么...
--编辑--
还有错误信息:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\ranma\cogs\Events.py", line 159, in on_message
await message.channel.send(embed=embed)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\abc.py", line 856, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed, nonce=nonce)
File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\http.py", line 225, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required
这是我更新后的代码:
import discord
from discord.ext import commands
from discord import Activity, ActivityType
import json
import datetime
import random
epoch = datetime.datetime.utcfromtimestamp(0)
time_diff = round((datetime.datetime.utcnow() - epoch).total_seconds())
def load_counters():
with open('./data/counters.json', 'r') as f:
counters = json.load(f)
return counters
def save_counters(counters):
with open('./data/counters.json', 'w') as f:
json.dump(counters, f, indent=4)
class Events(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
await self.client.change_presence(activity=Activity(name=f"r?help | in {len(self.client.guilds)} servers", type=ActivityType.playing))
print(" ")
print("License")
print(" ")
print("Copyright (c) Joshua Lewis")
print(" ")
print("Permission is hereby granted, free of charge, to any person obtaining a copy")
print("of this software and associated documentation files (the Software), to deal")
print("in the Software without restriction, including without limitation the rights")
print("to use, copy, modify, merge, publish, distribute, sublicense, and/or sell")
print("copies of the Software, and to permit persons to whom the Software is")
print("furnished to do so, subject to the following conditions:")
print(" ")
print("The above copyright notice and this permission notice shall be included in all")
print("copies or substantial portions of the Software.")
print(" ")
print("THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR")
print("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,")
print("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE")
print("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER")
print("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,")
print("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE")
print("SOFTWARE.")
print("Connecting to Discord API")
print("...")
print("......")
print(".........")
print(f"Logged in as : {self.client.user.name}#{self.client.user.discriminator}")
print("Collecting list of connected guilds")
print("...")
print("......")
print(".........")
print("Connected Guilds:")
print(f"{self.client.guilds}")
def check_all_message(check_for, message):
if check_for in message.content:
return True
elif check_for in message.embed:
return True
@commands.Cog.listener()
async def on_message_delete(self, message):
if not message.author.bot:
guild = message.author.guild
author = message.author
ch = message.channel
content = message.content
orange = discord.Color.dark_orange()
for channel in guild.channels:
if str(channel.name) == "log":
msg_del = str(f"""```css\n{content}```""")
aut_name = str(f"""```css\n{author.name}```""")
ch_name = str(f"""```css\n{ch.name}```""")
embed = discord.Embed(color=orange, timestamp=message.created_at)
embed.set_author(name="Message Deleted", icon_url=self.client.user.avatar_url)
embed.add_field(name=f"Message", value=msg_del, inline=False)
embed.add_field(name=f"Message Author", value=aut_name, inline=False)
embed.add_field(name=f"Channel", value=ch_name, inline=False)
embed.set_thumbnail(url=author.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
print(f'message: {content} by {author.name} was deleted in {ch.name}')
@commands.Cog.listener()
async def on_member_join(self, ctx, member):
if not ctx.author.bot:
guild = ctx.guild
msg = ctx.message
gold = discord.Color.dark_gold()
user_join = str(f"""```css\n{member.name} has entered {guild.name}.```""")
for channel in guild.channels:
if str(channel.name) == "log":
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="Use Joined", value=user_join, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_image(url=member.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, ctx, member):
if not ctx.author.bot:
guild = ctx.guild
msg = ctx.message
red = discord.Color.dark_red()
for channel in guild.channels:
if str(channel.name) == "log":
user_left = str(f"""```css\n{member.name} has left {guild.name}""")
embed = discord.Embed(color=red, timestamp=msg.created_at)
embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
embed.add_field(name="User Left", value=user_left, inline=False)
embed.set_image(url=member.avatar_url)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await channel.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
if not message.author.bot:
msg = message
guild = message.guild
gold = discord.Color.dark_gold()
bad_list = ["fuck",
"bitch",
"slut",
"dick",
"ass",
"dike",
"cunt",
"pussy",
"nigger",
"kkk",
"negro",
"cracka",
"jew",
"honkie"]
responses = ["I hope you didn't kiss your mother with that mouth....",
".....some people these days..... need to good switch to the [REDACTED]",
"Who taught you to use such filthy language?!?",
"Oh yes, talk dirty to me....",
"You FILTHY CASUAL! You need to learn better swears!",
"You're choice in words is reassuring. I know that you will never be anything now.",
"FUCK! Another one slipped through! GRAB THE RAID!",
"SHIT! SHIT! WE GOT ONE! WE FINALLY GOT ONE! GET THE HAMMER!"]
for bad_word in bad_list:
if bad_word in message.content:
return
response = random.choice(responses)
c_r = str(f"""```css\n{response}```""")
embed = discord.Embed(color=gold, timestamp=msg.created_at)
embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
embed.add_field(name="⚠", value=c_r, inline=False)
embed.set_thumbnail(url=self.client.user.avatar_url)
embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
await message.channel.send(embed=embed)
def setup(client):
client.add_cog(Events(client))
每当我 运行 命令时,这个人就会无休止地发送垃圾邮件。