How to put a user who used a command in a .json/.txt file [DISCORD.JS] - file

When someone use a command of my bot, like: /ban Player123 ReasonXYZ. I want the User who got banned with the reason and the user who banned Player123 is in a file named "banlist.json"
Sorry for bad english
const banlogmsg = message.author.tag + ' | ' + (banreason) + ' | ' (bannedplayer)
fs.writeFileSync('./banlog.json', JSON.stringify(banlogmsg))

I will show you how to actually send the file in a message. It's also better to use Buffer (integrated into nodejs) instead of fs.
let channel = message.channel;
let banlogmsg = message.author.tag + ' | ' + (banreason) + ' | ' (bannedplayer);
channel.send({files:[{attachment:Buffer.from(JSON.stringify(banlogmsg)),name:`banlog.json`}]});
I hope that answers your question.

Related

Making a discord bot and the way I'm adding roles is causing crashes

trying to make a level system that adds roles at certain levels but the bot is crashing everytime saying that at msg.member.roles.add() giving me a can't read properties of null (reading roles)
if (Date.now() - userStats.last_message > 60000) {
userStats.xp += between(15, 25);
userStats.last_message = Date.now();
//setup what xp needs for levels and reseting/setting levels and xp and adding roles for
certain levels
const xpToNextLevel = 5 * Math.pow(userStats.level, 2) + 50 * userStats.level + 100;
if (userStats.xp >= xpToNextLevel) {
userStats.level++;
userStats.xp = userStats.xp - xpToNextLevel;
msg.channel.send(msg.author.username + ' has increased their chubee faith level to ' +
userStats.level + ' <a:pepesimp:881812231208181790> \n');
if (userStats.level >= 1 && userStats.reached_level_1 === 0) {
userStats.reached_level_1 = 1;
msg.member.roles.add(chubee_follower);
msg.channel.send(msg.author.username + ' is now a chubee follower. Welcome
<a:chubee_pat:881808870681481216>');
You may need to check if member is defined in the message before trying to give the role. This is because there are some cases (like DMing the bot) where member is not defined in the message.
You can do this by changing
msg.member.roles.add(chubee_follower);
for
if(msg.member) msg.member.roles.add(chubee_follower);

Discord Bot shuts down whenever a user sends it a dm

My bot saves chat logs, it works perfectly until someone dms the bot. Here is the code that logs messages.
console.log(message.author.username, "||", message.channel.name, "-", message.content);
let channel = message.channel.name;
var readmessagefile = fs.readFileSync('./txt-files/logs.txt', 'utf-8');
var writemessagefile = fs.writeFileSync('./txt-files/logs.txt', 'Time - ' +
message.createdAt + ' Channel: ' + channel + " ||" + ' User - ' + message.member.user.username + ': ' +
message.content + "\n" + readmessagefile);
I'm trying to figure out a way to completely ignore dms so it doesn't mess anything up.
Here is the error:
C:\Documents\Projects\DiscordBot\commands\logs.js:11
message.createdAt + ' Channel: ' + channel + " ||" + ' User - ' + message.member.user.username + ': ' +
^
TypeError: Cannot read property 'user' of null
You did not initiate the user field (It's a Null) in object member that it a field in the var message
According to the message.member docs:
Represents the author of the message as a guild member. Only available if the message comes from a guild where the author is still a member
The problem is that DMs are not sent in a guild, and thus message.member returns null. You should be using message.author which also has a username property, and is available globally.
message.member.user and message.author technically return the same thing. message.author is the User object of whoever authored the message. message.member is the GuildMember object of whoever authored the message. GuildMember.user is the User object of a GuildMember.
They both return the same thing, but one takes an extra step to do so.
Author >> User (message.author)
Author >> GuildMember >> User (message.member.user)
Also, you can improve your code readability using template literals
var writemessagefile = fs.writeFileSync(
'./txt-files/logs.txt',
`Time - ${message.createdAt} Channel: ${channel} || User - ${message.author.username}: ${message.author.content}\n${readmessagefile}`
);

Knockout.js console.log observable array

tried to console.log the stage of the observable array content via JSON.stringify as usual, but no success. I see the length changes, but not the content.
Code:
arr.push(new Course('New title ' + randomCourse, 'New price ' + randomCourse));
console.log('CourseList: ' + arr().length + ' | ' + JSON.stringify(arr()));
Console:
CourseList: 5 | [{},{},{},{},{}]
CourseList: 7 | [{},{},{},{},{},{},{}]
CourseList: 9 | [{},{},{},{},{},{},{},{},{}]
CourseList: 11 | [{},{},{},{},{},{},{},{},{},{},{}]
You should probably use ko.toJS() to convert the observable properties into values:
console.log('CourseList: ' + arr().length + ' | ' + JSON.stringify(ko.toJS(arr())));
Hm, suddenly became not so simple and absolutely no any errors in debug.
Task is to push the array items to obsarvable array before other manipuletion.
Function (console if commented):
this.startCoursesList = function () {
if (arr.length === 0) {
startCourses.forEach(function (item, i) {
arr.push(new Course(startCourses[i].title, startCourses[i].price, startCourses[i].reqs));
});
// console.log(JSON.stringify(ko.toJS(arr())));
}
};
Everything working great, console is clear, but everything failed if I use JSON.stringify(ko.toJS(arr())). Suddenly I got the finction execution loop and arr.length check if not working. I also got the loop in console on any click event:
[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]
[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]
[{"title":"HTML/CSS","price":32000,"reqs":["Internet","Notepad++"]},{"title":"Yoga","price":7000,"reqs":[""]},{"title":"Darts","price":9500,"reqs":["Bomb","Worms"]}]

Apache Camel: How to download multiple files from SFTP with Premove, Move and MoveFailed options?

I have two file names in following format:
Gontagrator_1.xml
Gontagrator_2.xml
As of now i am picking just Gontagrater_1.xml and rename it to processing and failed once done.
+ "&fileName=" + sftpFileName
+ "&preMove="+sftpFileName+".$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.processing"
+ "&move="+sftpFileName+".$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}"
+ "&moveFailed="+sftpFileName+".$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.failed"
Now Gontagrator_2 comes into picture. It is suggested to create separate routes for both.
Can we download both in one route and rename accordingly? If yes, what values i need to pass?
Update1: There are multiple files with different names but i need to use both above file names only
update 2: Whole from component is:
"{{m.protocol}}://{{m.hostname}}{{t.directory}}"
+ "?username={{m.username}}"
+ "&password={{m.password}}"
+ "&download=true"
+ "&useList=false"
+ "&stepwise=false"
+ "&disconnect=true"
+ "&passiveMode=true"
+ "&reconnectDelay=10000"
+ "&bridgeErrorHandler=true"
+ "&delay=30000"
//+ "&fileName=" + sftpFileName
+ "&include="+ sftpFileName
+ "&preMove=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.processing"
+ "&move=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}"
+ "&moveFailed=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.failed"
+ "&readLock=idempotent-changed"
+ "&idempotentRepository=#infinispan"
+ "&readLockRemoveOnCommit=true")
.onException(GenericFileOperationFailedException.class)
.onWhen(exchange -> {
Throwable cause = exchange.getException(GenericFileOperationFailedException.class).getCause();
return (cause != null && cause.toString().equalsIgnoreCase("2: No such file"));
}).handled(true)
.logExhausted(true)
.logExhaustedMessageHistory(true)
.log("Could not find file")
.end()
.log("Downloading xml file")
//.to(archiveReceivedFile(sftpFileName))
.split(body().tokenizeXML("ERequest", "ERequests")).streaming()
.inOnly(E_QUEUE)
Yes, you can download all files in one route.
You need to
Remove fileName option (such that the route will pick all file)
Use file expression language (file:onlyname) to refer to filename currently handled by Camel SFTP component
+ "&preMove=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.processing"
+ "&move=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}"
+ "&moveFailed=$simple{file:onlyname}.$simple{date:now:yyyy-MM-dd'T'hh-mm-ss}.failed"
Use include option to control file to be picked up (REGEX to match file name pattern)
+ "&include=Gontagrator_(1|2)\.xml"

XMPP implementation in silverlight authentication returns failure

I am trying to implement Xmpp protocol in silverlight and trying to connect to Facebook, here I am getting everything correct until <challenge .. > obtained from server.
I am using X Facebook platform authentication.
I have done this with following code:
byte[] ch = Convert.FromBase64String(message.challenge);
string challenge = System.Text.Encoding.UTF8.GetString(ch, 0, ch.Length);
string response = "";
long callId = DateTime.UtcNow.Ticks;
MD5 md = new MD5();
String signature1 = "api_key=203366556348506"
+ "call_id=" + callId
+ "method=auth.xmpp_login"
+ param[2]
+ "session_key=" + messageClient.SessionKey
+ "v=1.0"
+ messageClient.AppSecret;
md.Value = signature1;
response = "method=auth.xmpp_login&api_key=203366556348506&session_key=bc6d6e00462cc2bb73a824bd.4-100001565408667&call_id=" + callId + "&sig=c47d741cb8f18c4e78b990f48e2f63aa&v=1.0&" + param[2];
message.Request = "<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(response)) + "</response>";
this.messageClient.SendMessageAsync(message);
But I am getting following message from server:
<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/></failure>
Please let me know where I am going wrong.
Try following code:
String signature1 = "api_key=" + messageClient.ApiKey
+ "call_id=" + callId
+ "method=auth.xmpp_login"
+ param[2]
+ "session_key=" + messageClient.SessionKey
+ "v=1.0"
+ messageClient.AppSecret;
md.Value = signature1;
response = "method=auth.xmpp_login&api_key=" + messageClient.ApiKey + "&session_key=" + messageClient.SessionKey + "&call_id=" + callId + "&sig=" + md.FingerPrint.ToLower() + "&v=1.0&" + param[2];
I have changed response string to the one above.
This has returned success for me. Hope this will help you.

Resources