Answer by Kennedi Henry
myid = '<@201909896357216256>'await client.send_message(message.channel, ' : %s is the best ' % myid)
Answer by Reign Olsen
Now you have to get your Bot User into a server. To do this, you should create an invite URL for it.,Go to the "OAuth2" tab. Then select "bot" under the "scopes" section.,So we have to do two more things to get our bot to run continuously:,Paste the URL into your browser, choose a server to invite the bot to, and click “Authorize”.
Add this code to main.py. (You can name the file something else if you like, just not discord.py.) I'll explain what all this code does shortly.
import discordimport osclient = discord.Client()@client.eventasync def on_ready(): print('We have logged in as {0.user}'.format(client))@client.eventasync def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!')client.run(os.getenv('TOKEN'))
Inside the file add the following line, including your actual token you copied previously:
TOKEN=[paste token here]
Here is the updated code. After the code, I'll explain the new parts.
import discordimport osimport requestsimport jsonclient = discord.Client()def get_quote(): response = requests.get("https://zenquotes.io/api/random") json_data = json.loads(response.text) quote = json_data[0]['q'] + " -" + json_data[0]['a'] return(quote)@client.eventasync def on_ready(): print('We have logged in as {0.user}'.format(client))@client.eventasync def on_message(message): if message.author == client.user: return if message.content.startswith('$inspire'): quote = get_quote() await message.channel.send(quote)client.run(os.getenv('TOKEN'))
Add the following list after the sad_words
list you created:
starter_encouragements = [ "Cheer up!", "Hang in there.", "You are a great person / bot!"]
Here is the updated code:
async def on_message(message): if message.author == client.user: return msg = message.content if msg.startswith('$inspire'): quote = get_quote() await message.channel.send(quote) if any(word in msg for word in sad_words): await message.channel.send(random.choice(starter_encouragements))
Answer by Aila McCormick
Note that while the term used in Discord’s user interface is Server, the term used in the developer documentation and API is Guild. Once we move on to talking about technical topics, we will switch to talking about Guilds. The two terms are interchangeable.,I receive a 200 status code, and I get the role granted to me in the server.,The log channel ID should be added to the constants section of bot.js.,The libraries officially vetted by Discord are generally mature, well-documented, and feature full coverage of the Discord API. Most bot developers will never have a good reason to develop a custom implementation, except out of curiosity, or bravery!
Assuming you have Node.js installed, create a project and install Eris (the bot library we’ll use), Express (a web application framework we’ll use to create a webhook listener), and body-parser (for parsing webhook bodies).
mkdir premium_botcd premium_botnpm initnpm install eris express body-parser
(GitHub code link: https://github.com/mistval/premium_bot/blob/master/src/bot_step1.js)
const eris = require('eris');// Create a Client instance with our bot token.const bot = new eris.Client('my_token');// When the bot is connected and ready, log to console.bot.on('ready', () => { console.log('Connected and ready.');});// Every time a message is sent anywhere the bot is present,// this event will fire and we will check if the bot was mentioned.// If it was, the bot will attempt to respond with "Present".bot.on('messageCreate', async (msg) => { const botWasMentioned = msg.mentions.find( mentionedUser => mentionedUser.id === bot.user.id, ); if (botWasMentioned) { try { await msg.channel.createMessage('Present'); } catch (err) { // There are various reasons why sending a message may fail. // The API might time out or choke and return a 5xx status, // or the bot may not have permission to send the // message (403 status). console.warn('Failed to respond to mention.'); console.warn(err); } }});bot.on('error', err => { console.warn(err);});bot.connect();
To inform the bot of payment, we will issue a command that looks like this:
pb!addpayment @user_mention payment_amount
(GitHub code link: https://github.com/mistval/premium_bot/blob/master/src/bot_step2.js)
const eris = require('eris');const PREFIX = 'pb!';const bot = new eris.Client('my_token');const commandHandlerForCommandName = {};commandHandlerForCommandName['addpayment'] = (msg, args) => { const mention = args[0]; const amount = parseFloat(args[1]); // TODO: Handle invalid command arguments, such as: // 1. No mention or invalid mention. // 2. No amount or invalid amount. return msg.channel.createMessage(`${mention} paid $${amount.toFixed(2)}`);};bot.on('messageCreate', async (msg) => { const content = msg.content; // Ignore any messages sent as direct messages. // The bot will only accept commands issued in // a guild. if (!msg.channel.guild) { return; } // Ignore any message that doesn't start with the correct prefix. if (!content.startsWith(PREFIX)) { return; } // Extract the parts of the command and the command name const parts = content.split(' ').map(s => s.trim()).filter(s => s); const commandName = parts[0].substr(PREFIX.length); // Get the appropriate handler for the command, if there is one. const commandHandler = commandHandlerForCommandName[commandName]; if (!commandHandler) { return; } // Separate the command arguments from the command prefix and command name. const args = parts.slice(1); try { // Execute the command. await commandHandler(msg, args); } catch (err) { console.warn('Error handling command'); console.warn(err); }});bot.on('error', err => { console.warn(err);});bot.connect();
(GitHub code link: https://github.com/mistval/premium_bot/blob/master/src/bot_step3.js)
const eris = require('eris');const PREFIX = 'pb!';const BOT_OWNER_ID = '123456789';const bot = new eris.Client('my_token');const commandForName = {};commandForName['addpayment'] = { botOwnerOnly: true, execute: (msg, args) => { const mention = args[0]; const amount = parseFloat(args[1]); // TODO: Handle invalid command arguments, such as: // 1. No mention or invalid mention. // 2. No amount or invalid amount. return msg.channel.createMessage(`${mention} paid $${amount.toFixed(2)}`); },};bot.on('messageCreate', async (msg) => { try { const content = msg.content; // Ignore any messages sent as direct messages. // The bot will only accept commands issued in // a guild. if (!msg.channel.guild) { return; } // Ignore any message that doesn't start with the correct prefix. if (!content.startsWith(PREFIX)) { return; } // Extract the parts and name of the command const parts = content.split(' ').map(s => s.trim()).filter(s => s); const commandName = parts[0].substr(PREFIX.length); // Get the requested command, if there is one. const command = commandForName[commandName]; if (!command) { return; } // If this command is only for the bot owner, refuse // to execute it for any other user. const authorIsBotOwner = msg.author.id === BOT_OWNER_ID; if (command.botOwnerOnly && !authorIsBotOwner) { return await msg.channel.createMessage('Hey, only my owner can issue that command!'); } // Separate the command arguments from the command prefix and name. const args = parts.slice(1); // Execute the command. await command.execute(msg, args); } catch (err) { console.warn('Error handling message create event'); console.warn(err); }});bot.on('error', err => { console.warn(err);});bot.connect();
Answer by Conrad Campos
2)You must have Python installed.,After the installation was successful, open your code editor, and mane the file ‘bot.py’.,Also remember, that if you want to summon your bot, your calling command should be prefixed by the “command_prefix”.,Now when that is done, install discord in your system.
In your cmd, run this command:
pip install discord
Import the necessary dependencies:
import discordfrom discord.ext import commands
Naming the client variable ‘client’
client = commands.Bot( command_prefix=" / " )
Now, for knowing the up-status of the bot:
@client.eventasync def on_ready( ): print("Bot is ready")
Now when the bot is ready, we also want to respond to the “Hello”s entered by the server users.
@client.eventasync def hello( ): await ctx.send("Hi")
To run the bot, we need the token that will be provided to you in the ‘Bot section’ that you visited while creating the bot.
client.run("Token ")
Open CMD, and run:
bot.py
If that does not work, try
python bot.py
Now head over to your server and check by typing the test query, which in our case was
'/hello'
We see that our bot successfully replies:
"Hi".
Similarly, code to create a bot that welcomes new members would be:
import osimport discordfrom dotenv import load_dotenvload_dotenv()TOKEN = os.getenv('DISCORD_TOKEN')client = discord.Client()@client.eventasync def on_ready(): print(f'{client.user.name} has joined Discord!')@client.eventasync def on_member_join(member): await member.create_dm() await member.dm_channel.send( f'Hello {member.name}!! Welcome to Our Discord Server!' )client.run(TOKEN)
Related
How do I randomize what a discord bot says? Counting discord bot python Discord.py bot dont have certificate Python discord discord.py disable remove help command Discord python on role grant event Python discord bot wait for response Speak by a discord bot in python Programming a Discord bot in Python- In on_raw_reaction_add, how do I tell if the message has an image? Discord - Screenshot Embed Messages Colorcodes Discord.py I am currently learning to make a discord bot. I want to create a switch statement Discord Python Reaction Role How to DM everyone in a Discord server with discord.py? Bot discord if someone click reaction change message and delete reaction discord.py Cooldown for on_message in discord.py How to setup discord.py bot Python - How To Make A Discord Bot Command Have Multiple “Call Words” [duplicate] Python discord py make embed Discord Bot Can't Get Channel by Name How to make a discord bot