i have telegram bot on nodejs. I use node-telegram-bot-api.
my processing command /start
bot.onText(/\/start/, async (msg) => {.....
lots of code
.....
});
so that the main page of js is not huge and easy to read, I want to transfer the start processing to another file. What is the best way to do it? right now, is this the right decision?
bot.onText(/\/start/, async (msg) => {
await start(bot,msg)
});
start.js
export const start = async (msg, bot) => {}
Related
I tried messing around with it and couldn't get it to work - all I want is for it to send in the channel that the user initiated the bot to talk.
client.once('ready', async () => {
// [beta]
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
client.channels.fetch("/*the channel where channel.send will go to*/").then((c) => {
channel = c;
})
console.log(`Logged in as ${client.user.tag}!`);
});
It's quite easy, in fact. If you haven't created the client.on("messageCreate", message => {}); event handler, I very strongly recommend creating it in the main file (if you use multiple files). Then, all you have to do is use message.channel.send(); inside those curly brackets {} to send message in the channel the user initiated the bot to talk. It's a good idea to check out the discord.js guide: https://discordjs.guide/#before-you-begin and watch YouTube tutorials on discord.js v13.
I am trying create a telegram bot using node.js (telegraf). But I am facing problems while using on, hears, command. For Example, if I use hears before command, hears listens the command. sometimes it went on.
I modified my code to similar example. Here the command stringx not calling, but it calls to hears.
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.on('text', (ctx) => ctx.reply('👍'))
bot.hears('string', (ctx) => ctx.reply('Hey there'))
bot.command('stringx', (ctx) => ctx.reply('Hello'))
bot.launch();
Similar things happened with on('text',callback), on('message',callback), on('pinned_message',callback).
What is the order of type parameters listening using on.(Source (Type parameters): https://telegraf.js.org/classes/Telegraf.html#on)?
What is the order of placing on, hears, command?
Thanks in Advance
You need to call next() to continue the middleware chain or else the first satisfied query will be the only one that runs.
await next() // runs next middleware
I need some help with a code in discord.js where I delete the existing categories and channels and then make new ones. My code edits the icon and guild name so now I'm moving onto channels and whatnot. No, this is not a nuker, I'm trying to make a server rebuilder or remodeler and things similar to that. Anyways, here is my code and by the bottom is where I'd like to implement the channel deleting and replacing.
const Discord = require('discord.js');
const client = new Discord.Client();
const guild = new Discord.Guild();
const { prefix, token } = require('./config.json');
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
client.on("message", async (message) => {
if (message.content == "server") {
try {
await message.guild.setIcon("./icon.png");
await message.guild.setName("server");
message.channel.send("Successfully made server.");
} catch {
message.channel.send("Unknown error occurred while making server.");
}
}
});
If anyone could help with this, please let me know.
Your question is too broad, you should try to narrow it to something specific that you are having issues with, like #Skulaurun Mrusal told you to. However, I can give you some tips on where to start:
You can access a <Guild>'s <GuildChannelManager> - a class that gives you some ways of managing the guild channels, such as deleting or creating them - through <Guild>.channels.
If you'd like to delete a channel from this <Guild> you would do <Guild>.cache.channels.find(channel => channel.name === 'channel-name').delete()
While if you wanted to create one, you would do: <Guild>.channels.create(...).
Don't forget you need the MANAGE_CHANNELS permission to do such operations. I hope this can help you out.
I am having a problem with figuring out how my NodeJS bot can read and write data to a config.json file. Apart from that, I do not know how to detect arguments sent with a Bot Command. Therefore my Questions are as following:
How to Read / Write Data to a config.json?
How to detect args sent with Bot Command?
Thank you in Advance :)
-Luis
I have a NodeJS discord bot as well and for importing settings I use the following. I have not found the need to write to a json file, though hopefully this helps solve the first part of your question.
Code sample
fs.readFile(file, 'utf8', (err, data) => {
var tree = JSON.parse(data);
token = tree.token;
});
config file
{
"token":""
}
For getting arguments from a command, you can do something like this:
client.on("message", async message => {
const param = message.content.split(' ');
const command = param[0].substr('!'.length);
const arguments = param.slice(1);
})
Here is my main discord bot file with such code bits. It is pretty cluttered with other stuff so beware. https://github.com/NicholasLKSharp/DiscordJSMusicBot-SpotifyPuller/blob/master/main.js
Problem
I have a node app deployed on Heroku and I'm trying to use Heroku Scheduler to execute tasks since node-cron doesn't work with Heroku.
The scheduler runs but it always exits with code 0. A picture of the error message is below.
I've been working on this for 4 hours already with no luck so if anyone has any suggestions that would be amazing!
Code
Here's the code in the file I'm using with Heroku Scheduler. I have it scheduled to run every 10 minutes. The getActiveComps function calls a function from another file in the node app that makes calls to an external API and then writes data to MongoDB via Mongoose.
#!/app/.heroku/node/bin/node
const getActiveComps = require('../api/functions/schedulerFunctions.js');
console.log('scheduler ran');
(async () => {
console.log('before');
await getActiveComps();
console.log('after');
})();
I never did solve the problem of running async function in a scheduled job, but I did a workaround. What I did was to make an internal API that ran the function, and make the scheduled job call the internal API to run the task. This may or may not work for you.
Defined a new API in my router:
router.get('/refresh', (req, res, next) => {
//this is the function that I needed the scheduler to run.
utils.getData().then(response => {
res.status(200).json(response);
}).catch(err => {
res.status(500).json({
error: err
});
});
})
scheduled_job.js:
const fetch = require('node-fetch');
async function run() {
try {
let res = await fetch(process.env.REFRESH_PATH);
result = await res.json();
console.log(result);
} catch (err) {
console.log(err);
}
}
run();
Of course, you should set your API path inside the heroku config vars.
Hope this helps you.