Discord bot buton ve menü nasıl yapılır?

arda.nb01

Centipat
Katılım
24 Ocak 2024
Mesajlar
281
Daha fazla  
Cinsiyet
Erkek
Arkadaşlar şöyle kodlarım var. Kendim buton yapmak istedim fakat yapamıyorum yeniyim bot yapmada. İşte kodlar...

Kod:
//bot.js
const fs = require('fs');
const path = require('path');
const express = require('express');
const { Client, Intents } = require('discord.js');

const app = express();
const client = new Client({
 intents: [
 Intents.FLAGS.GUILDS,
 Intents.FLAGS.GUILD_MESSAGES
 ]
});

let botActive = false;
let totalMessages = 0;
let startTime = null;

// Middleware to parse JSON and form data.
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static files (index.html, scripts.js, styles.css gibi)
app.use(express.static('public'));

// Routes.
app.get('/', (req, res) => {
 res.sendFile(__dirname + '/public/index.html');
});

app.post('/control', (req, res) => {
 const { action } = req.body;

 if (action === 'start' && !botActive) {
 client.login('MTI1Mjk3ODI0ODA3ODMzMTkwNQ.GC7FgI.PaaOaZxhUcayWNj-dOcHvFDldPmad6o5Sr7mI0') // Discord bot token'i buraya ekleyin.
 .then(() => {
 botActive = true;
 startTime = new Date();
 console.log('Bot başlatıldı.');
 res.json({ status: 'success', message: 'Bot başlatıldı.' });
 })
 .catch(error => {
 console.error('Bot başlatılırken hata oluştu:', error);
 res.status(500).json({ status: 'error', message: 'Bot başlatılırken bir hata oluştu.' });
 });
 } else if (action === 'stop' && botActive) {
 client.destroy();
 botActive = false;
 totalMessages = 0;
 startTime = null;
 console.log('Bot durduruldu.');
 res.json({ status: 'success', message: 'Bot durduruldu.' });
 } else {
 res.status(400).json({ status: 'error', message: 'Geçersiz istek.' });
 }
});

// Discord message listener.
client.on('messageCreate', message => {
 if (!message.author.bot) {
 totalMessages++;

 // Komutları işlemek için prefix kontrolü.
 if (message.content.startsWith('!')) {
 const args = message.content.slice(1).trim().split(/ +/);
 const commandName = args.shift().toLowerCase();

 const commandFile = path.resolve(__dirname, 'commands', `${commandName}.js`);

 // Komut dosyasını kontrol edip çalıştırma.
 if (fs.existsSync(commandFile)) {
 const command = require(commandFile);
 try {
 command.execute(message, args);
 } catch (error) {
 console.error(error);
 message.reply('Komut çalıştırılırken bir hata oluştu.');
 }
 }
 }
 }
});

// Function to calculate uptime.
function getUptime() {
 if (!startTime) return 'Bot henüz başlatılmadı.';
 const currentTime = new Date();
 const uptime = currentTime - startTime;
 const days = Math.floor(uptime / (1000 * 60 * 60 * 24));
 const hours = Math.floor((uptime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
 const minutes = Math.floor((uptime % (1000 * 60 * 60)) / (1000 * 60));
 return `${days} gün, ${hours} saat, ${minutes} dakika`;
}

// Endpoint to get bot stats.
app.get('/stats', (req, res) => {
 const uptime = getUptime();
 res.json({
 totalMessages: totalMessages,
 uptime: uptime.
 });
});

// Listen on the specified port.
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
 console.log(`Sunucu ${PORT} portunda çalışıyor.`);
});

Kod:
//buton.js
const { MessageButton } = require('discord.js');

module.exports = {
 data: {
 name: 'yardım',
 description: 'Yardım butonları gösterir.'
 },
 async execute(message, args, client) {
 if (message.content.startsWith('!yardım')) {
 const button = new MessageButton()
 .setStyle('SUCCESS')
 .setLabel('Buraya Tıkla')
 .setCustomId('button1');

 const button2 = new MessageButton()
 .setStyle('LINK')
 .setLabel('Buraya Tıkla')
 .setURL('http://oyuncularsehri.com');

 const button3 = new MessageButton()
 .setStyle('DANGER')
 .setLabel('Buraya Tıkla')
 .setCustomId('button2');

 await message.channel.send("Oyuncular Şehri forum linkini görmek için;", {
 components: [[button, button2, button3]]
 });

 const filter = i => i.customId === 'button1' || i.customId === 'button2';
 const collector = message.channel.createMessageComponentCollector({ filter, time: 15000 });

 collector.on('collect', async i => {
 if (i.customId === 'button1') {
 await i.reply({ content: 'Yardım Menüsü Buraya Gelecek', ephemeral: true });
 } else if (i.customId === 'button2') {
 await i.reply({ content: 'http://oyuncularsehri.com/', ephemeral: true });
 }
 });

 collector.on('end', collected => {
 console.log(`Collected ${collected.size} interactions.`);
 });
 }
 }
};
 

Şu paket işinize yarar diye düşünüyorum.
 

Şu paket işinize yarar diye düşünüyorum.

JS ile yazıyorum ben gönderdiğiniz Python galiba.
 
MessageActionRow ile row oluşturup components kısmına onu vermeniz gerekiyor. Bir dahakine zahmet olmazsa hangi discord.js versiyonunu kullandığınızı da yazarsanız iyi olur.
JavaScript:
const button = new MessageButton()
 .setStyle('SUCCESS')
 .setLabel('Buraya Tıkla')
 .setCustomId('button1');

 const button2 = new MessageButton()
 .setStyle('LINK')
 .setLabel('Buraya Tıkla')
 .setURL('http://oyuncularsehri.com');

 const button3 = new MessageButton()
 .setStyle('DANGER')
 .setLabel('Buraya Tıkla')
 .setCustomId('button2');

const row = new MessageActionRow().addComponents(button, button2, button3);

await message.channel.send("Oyuncular Şehri forum linkini görmek için;", {
 components: [row]
 });
 
MessageActionRow ile row oluşturup components kısmına onu vermeniz gerekiyor. Bir dahakine zahmet olmazsa hangi discord.js versiyonunu kullandığınızı da yazarsanız iyi olur.
JavaScript:
const button = new MessageButton()
 .setStyle('SUCCESS')
 .setLabel('Buraya Tıkla')
 .setCustomId('button1');

 const button2 = new MessageButton()
 .setStyle('LINK')
 .setLabel('Buraya Tıkla')
 .setURL('http://oyuncularsehri.com');

 const button3 = new MessageButton()
 .setStyle('DANGER')
 .setLabel('Buraya Tıkla')
 .setCustomId('button2');

const row = new MessageActionRow().addComponents(button, button2, button3);

await message.channel.send("Oyuncular Şehri forum linkini görmek için;", {
 components: [row]
 });

Pardon hocam bir dahakine eklerim sizinle iletişim kuracağım bir adres var mı?
 
Burada konu oluşturmanız daha iyi olur. Sorununuz çözüldü mü?

Hocam şöyle konunun başındaki kod iptal oldu sıfırdan birleştirdiğim kod:

Kod:
const { Client, Intents, MessageActionRow, MessageButton } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS] });

client.once('ready', () => {
 console.log('Bot is ready!');
});

const button = new MessageButton()
 .setStyle('SUCCESS')
 .setLabel('Buraya Tıkla')
 .setCustomId('button1');

 const button2 = new MessageButton()
 .setStyle('LINK')
 .setLabel('Buraya Tıkla')
 .setURL('http://oyuncularsehri.com');

 const button3 = new MessageButton()
 .setStyle('DANGER')
 .setLabel('Buraya Tıkla')
 .setCustomId('button2');

const row = new MessageActionRow().addComponents(button, button2, button3);

await message.channel.send("Oyuncular Şehri forum linkini görmek için;", {
 components: [row]
 });
client.login('MTI1NDUzNzE0ODQ5MzcyNTc3Ng.GXtR_h.EpgB_ZhPT2nw664VKmcRPJrhQfVJq3smUyGMa0');

Hata:
Await message. Channel. Send("oyuncular şehri forum linkini görmek için;", {
^^^^^

Syntaxerror: Await is only valid in async functions and the top level bodies of modules.
At wrapsafe (node:internal/modules/cjs/loader:1281:20)
At module. _compile (node:internal/modules/cjs/loader:1321:27)
At Module._extensions..js (node:internal/modules/cjs/loader:1416:10)
At module. Load (node:internal/modules/cjs/loader:1208:32)
At module. _load (node:internal/modules/cjs/loader:1024:12)
At function. Executeuserentrypoint [as runMain] (node:internal/modules/run_main:174:12)
At node:internal/main/run_main_module:28:49
 
await icin async blokta olman gerekiyor, yaziyor hata mesajinda.

Ya soyledigi gibi async block icinde await etmelisin ya da promise handle etmelisin callback yazarak.

Bunlar cok temel isler, bence kafandaki projeyi kisa sureligine rafa kaldirip async - await - promise mantigi uzerine basit bir calisma yap. Sonra sormana gerek kalmaz hatani pat diye gorursun.
 

Technopat Haberler

Geri
Yukarı