#CLIENT.event
async def on_message(message):
if ":cmonBrug:" in message.content:
await message.CHANNEL.send("Teste")
await CLIENT.process_commands(message)
ERROR: File "main.py", line 33, in on_message
await message.CHANNEL.send("Teste")
AttributeError: 'Message' object has no attribute 'CHANNEL'
Related
I'm developing a telegram bot to register user and save his data in db. And after the registration I can't see that data in sqlite3. I don't understand what`s the problem and how to fix it
async def db_start():
global db, cur
db = sq.connect('base.db')
cur = db.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS members(user_id TEXT PRIMARY KEY, name TEXT, phone TEXT, email TEXT, about TEXT, post TEXT, letters TEXT, box TEXT, donate TEXT)")
db.commit()
async def register(user_id):
user = cur.execute("SELECT 1 FROM members WHERE user_id == '{key}'".format(key=user_id)).fetchone()
if not user:
cur.execute("INSERT INTO members VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", (user_id, '', '', '', '', '', '', '', ''))
db.commit()
async def update(state, user_id):
async with state.proxy() as data:
cur.execute("UPDATE members SET name = '{}', phone = '{}', email = '{}', about = '{}', post = '{}', letters = '{}', box = '{}', donate = '{}' WHERE user_id == '{}'".format(data['name'], data['phone'], data['email'], data['about'], data['post'], data['letters'], data['box'], data['donate'], user_id))
db.commit()
Here is the db screens
db screen from sqlite3 db screen from pycharm
code from the main file
async def on_startup(_):
await db_start()
storage = MemoryStorage()
bot = Bot(token=config.TOKEN)
dp = Dispatcher(bot, storage=storage)
class ProfileStatesGroup(StatesGroup):
name = State()
phone = State()
email = State()
about = State()
post = State()
letters = State()
box = State()
donate = State()
def get_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/register'))
return kb
def get_cancel_kb() -> ReplyKeyboardMarkup:
kb = ReplyKeyboardMarkup(resize_keyboard=True)
kb.add(KeyboardButton('/cancel'))
return kb
#dp.message_handler(commands=['cancel'], state='*')
async def cmd_cancel(message: types.Message, state: FSMContext):
if state is None:
return
await state.finish()
await message.reply('text',
reply_markup=get_kb())
#dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message) -> None:
await message.answer("text", reply_markup=get_kb())
await register(user_id=message.from_user.id)
#dp.message_handler(commands=['register'])
async def cmd_create(message: types.Message) -> None:
await message.reply("text",
reply_markup=get_cancel_kb())
await ProfileStatesGroup.next()
# await ProfileStatesGroup.name.set()
#dp.message_handler(state=ProfileStatesGroup.name)
async def load_name(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['name'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.phone)
async def load_phone(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['phone'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.email)
async def load_email(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['email'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.about)
async def load_about(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['about'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.post)
async def load_post(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['post'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.letters)
async def load_letters(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['letters'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.box)
async def load_box(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['box'] = message.text
await message.reply('text')
await ProfileStatesGroup.next()
#dp.message_handler(state=ProfileStatesGroup.donate)
async def load_donate(message: types.Message, state: FSMContext) -> None:
async with state.proxy() as data:
data['donate'] = message.text
await update(state, user_id=message.from_user.id)
await message.reply("text")
await state.finish()
I will be very grateful if somebody helps me to find my problem :)
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="Cheapest coins on the market", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ?
Also seems like i need to post more details, don't pay attention to this :
Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
I have code like this:
#bot.command(pass_context=True)
#commands.has_any_role(admin, moderator, ghostluko)
async def ver(ctx,member:discord.Member = None):
role = ctx.guild.get_role(role_id=868210259284619324)
role1 = ctx.guild.get_role(role_id=905358001270046770)
await ctx.message.delete()
await member.add_roles(role)
await member.remove_roles(role1)
await ctx.send(f'{member} дал роль "{role}"')
after I add this, other commands start do not work
#bot.event
async def on_message(message):
embedbotreply = discord.Embed(description = f"Напишите help для подробной информации. Ваш префикс: {bot.command_prefix}", color = 0x8147fc)
if bot.user.mentioned_in(message):
await message.channel.send(embed = embedbotreply)
#bot.command()
async def ping(ctx):
embedping = discord.Embed(description = f" Мой пинг: {format(round(bot.latency, 1))} ms!", color = 0x8147fc)
await ctx.send(embed = embedping)
await ctx.message.delete()
Also, on_member_join do not work. I don't know what to do.
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
Try using await bot.process_commands(message) in your code and after this code you can use your other commands :
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('We are logged in!')
#bot.event
async def on_message(message):
if message.author==bot.user:
return
await bot.process_commands(message)
#bot.command()
async def ping(message) :
await message.channel.send("Pong!!")
bot.run("TOKEN")
Hope, this helps you !!
So I am trying to make a verify script so when a member join he/she has to write !verify and then he/she will get a rank on the discord so we won't get raided by bot's
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.author
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
}
module.exports.help = {
name: "verify" //Name of the command
}
And when I try this code out I get this error And I have tried to research it but I can't find anything on it
This is my error
message.channel.send(`${member} have been verifyed`).then(member.roles.add(myRole).tehn(msg => msg.delete({ timeout: 5000 })));
^
TypeError: Cannot read property 'add' of undefined
at Object.module.exports.run (C:\Users\lauri\Desktop\QuebecCity\utility\verify.js:12:76)
at Client.<anonymous> (C:\Users\lauri\Desktop\QuebecCity\index.js:257:33)
at Client.emit (node:events:376:20)
at MessageCreateAction.handle (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lauri\Desktop\QuebecCity\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (node:events:376:20)
roles is a property of the GuildMember object. You are unable to add roles to a User object (AKA message.author that returns the user object of the author of a message). From that instance, we would simply want to instead use the member property of the message object, resulting in message.member.
Final Code
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete()
const member = message.member
let myRole = message.guild.roles.cache.get("791724979435470889")
if (!message.channel.name.startsWith(`⚜ʙɪᴇɴ`)) return message.channel.send(`you have already been verified`).then(msg => msg.delete({ timeout: 5000 }));
message.channel.send(`${member} have been verifyed`).then(msg => msg.delete({ timeout: 5000 }));
member.roles.add(myRole)
}
module.exports.help = {
name: "verify" //Name of the command
}
so, im trying to make a reaction help with this code
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction == '➡️':
await ctx.send("NEEXT!")
return
elif reaction == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")
but when a reaction added, it dosen't do anything. Can someone help me? I want reaction help for 1week.
You need to use reaction.emoji when comparing to unicode emojis.
#client.command()
async def test(ctx):
msg = await ctx.send("Eh idk just react")
await msg.add_reaction("⬅️")
await msg.add_reaction("➡️")
def check(reaction, user):
return user == ctx.message.author and str(reaction.emoji) in ['⬅️', '➡️']
try:
reaction, user = await client.wait_for('reaction_add', timeout=5, check=check)
if reaction.emoji == '➡️':
await ctx.send("NEEXT!")
return
elif reaction.emoji == '⬅️':
await ctx.send("RETUUURN!")
return
except asyncio.TimeoutError:
await ctx.send("Timed out")