Discord.js Announce Command Slice Issue with Args - arguments

iv made an announce command for my bot, i have it outputting the contents of the message to a RichEmbed.
I have it set in IF statement
If users mentioned first then it removes the mention and sends it to the channel and displays embed with contents (args.slice(2))
ELSE just send the embed with args.slice(1) removing the command.
My problem is that they either both slice(1) or both slice(2) , despite me having them set differently
if (!user);
const embed = new Discord.MessageEmbed()
.setTitle(`${(args.slice(1).join(" "))}`, 'https://i.gyazo.com/898806671312f3585209cf0fd69341006.jpg')
.setColor(0x320b52)
.setTimestamp()
.setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/898806671312f3585209cf0fd69341006.jpg')
message.channel.send(embed);
}
else {
message.channel.send("<#" + user.id + ">")
const embed = new Discord.MessageEmbed()
.setTitle(`${(args.slice(2).join(" "))}`, 'https://i.gyazo.com/898806671312f358509cf0fd69341006.jpg')
.setColor(0x320b52)
.setTimestamp()
.setFooter('Requested by ' + message.author.tag, 'https://i.gyazo.com/898806671312f358509cf0fd69341006.jpg')
message.channel.send(embed);
}

Replace the ; in your first line with a {:
if (!user) {

Related

discord.py file append rewrite the file instead of appending

When I want to append something to a file (with the append mode), it just erases everything before writing what I would like to append.
I have an on_voice_state_update event, when triggered, it checks if the user joined a specific channel. If yes: it creates a voice channel with some permissions for the user who created the voice channel. It is also supposed to append to a file called member_channel.txt this: {member.id}:{the_member's_voice_channel.id} but instead of adding this at the end of the file, it first erases everything and then add what I want to add.
Here are the codes:
#bot.event
async def on_voice_state_update(member, before, after):
if after.channel is not None and after.channel.id == 1059553884286230608:
guild = bot.get_guild(966749409314504774)
everyone_role = discord.utils.get(guild.roles, id = 966749409314504774)
community_role = discord.utils.get(guild.roles, id = 1006304076331483256)
muted_role = discord.utils.get(guild.roles, id = 1059109986258653244)
global member_channel
member_channel = await guild.create_voice_channel(name = f"Vocal de {member.name}")
await member_channel.edit(category = discord.utils.get(get_guild().channels, id = 1057730051321372692))
await member_channel.set_permissions(member, connect = True, manage_channels = True, manage_permissions = True, priority_speaker = True, move_members = True)
await member_channel.set_permissions(everyone_role, view_channel = False)
await member_channel.set_permissions(community_role, view_channel = True)
await member_channel.set_permissions(muted_role, speak = False)
await member.move_to(member_channel)
with open("member_channel.txt", "a") as file: # THIS IS WHAT
file.write(str(member.id) + ":" + str(member_channel.id) + "\n") # IS'NT WORKING
print(f"[{await get_hour()}] {member.name} created a temporary voice channel.")
#then we want to delete the channel if it is empty and equal to a member's channel, and also delete the line in member_channel.txt corresponding to this member and channel
elif before.channel is not None and len(before.channel.members) == 0:
new_file_value = ""
try:
with open("member_channel.txt", "r") as file:
lines = file.readlines()
splited_lines = []
for line in lines:
splited_lines.append((line.split(":")))
for lines in splited_lines:
for line in lines:
line.replace("\n", "")
if str(before.channel.id) in line:
await before.channel.delete()
del splited_lines[line.index(str(before.channel.id))]
for line in splited_lines:
print(new_file_value)
new_file_value += line
for ele in line:
print(new_file_value)
new_file_value += line + ":"
with open("member_channel.txt", "w+") as file:
file.write(new_file_value)
print(f"[{await get_hour()}] I deleted the temporary voice channel {member_channel.name}.")
file.close()
file.close()
except NameError:
return

Overwriting the text in slot

I am designing a chat application. My query is that I am printing the message and name of the user in a chat box on pressing a send button in Qt. Every time I press the button instead of writing the new message in next line, it erases the previous message and overwrites it by showing the new message only.
Code:
QString str = ui->textEdit->toPlainText();
QString name= ui->textEdit->objectName();
ui->textBrowser->setText(name);
ui->textBrowser->setText(name + ": " + str);
std::cout<<endl;
setText() sets the text in the textEdit (and not appends what you have probably guessed), therefore your second setText() overwrites the first one.
QString str = ui->textEdit->toPlainText();
QString name= ui->textEdit->objectName();
QString oldMsg = ui->textBrowser->text();
QString newMsg = name + ": " + str;
ui->textBrowser->setText(oldMsg + "\n" + newMsg);

OpenWhisk - character sets?

I recently started using OpenWhisk and love it.
Everything seems to work real nice, except I have run into some issue which might be related to character sets / encoding.
E.g. when I use "Scandinavian characters", like æ, ø, å, I see this in the OpenWhisk Web Editor when calling an action / trigger with payload like:
{
"station": "Rådhuset",
"no2": 8.7,
"pm10": 6.5,
"pm25": 2.2,
"time": 1461348000,
"id": "Rådhuset-1461348000"
}
I get the following result / response payload:
{
"notify": "Station R??dhuset != R���dhuset"
}
The main function in the action called looks like this:
var payload = params.payload || params;
var station = 'Rådhuset';
if (station == payload.station) {
...
} else
return whisk.done({notify : 'Station ' + station + ' != ' + payload.station});
When running the action without these characters, e.g. "Kirkeveien", everything works fine.
Has anyone else run into similar situation?!
There is a known defect with non-ASCII characters. https://github.com/openwhisk/openwhisk/issues/252
A possible workaround is to encode the string (base64 encoding for example).
try encoding:
var payload = params.payload || params;
var station = 'Rådhuset';
if (station == payload.station) {
...
} else
return whisk.done({notify : 'Station ' + encodeURIComponent(station) + ' != ' + encodeURIComponent(payload.station)});

Using ctypes function in firefox ChromeWorker

I am trying to use a ChromeWorker to launch a background process, like so:
var worker = new ChromeWorker(data.url("stun-manager.js"));
worker.addEventListener('message', function(e) {
console.log(e.data);
}, false);
worker.postMessage({'cmd': 'start', 'msg': 'Hi'});
But where exactly do I declare all my ctypes and such? Interestingly, in stun-manager.js, if I have the following:
dump ("Message 1");
var {Cu} = require("chrome");
dump ("Message 2");
/*import js-ctypes */
var {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm")
var stun_driver = ctypes.open("C:\\Users\\derek_000\\Documents\\Visual Studio 2012\\Projects\\stunnel507\\stunnel507\\bin\\win32\\stun_driver.dll");
const launch_stun = stun_driver.declare("launch_stun", ctypes.default_abi, ctypes.int32_t, ctypes.int32_t, ctypes.char.ptr.ptr);
let argv_t = ctypes.ArrayType(ctypes.char.ptr);
let argc = 2;
let argv = new argv_t(argc);
var conf_path = "C:\\Users\\derek_000\\Documents\\Visual Studio 2012\\Projects\\stunnel507\\stunnel507\\stunnel.conf";
argv[0] = ctypes.char.array()(conf_path);
argv[1] = ctypes.char.array()(conf_path);
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'start':
self.postMessage("Value of launch_stun " + self.launch_stun);
self.postMessage('WORKER STARTED: ' + data.msg);
self.postMessage("debug" + self.argv_t);
self.postMessage("test: " + self.argv_t);
self.postMessage(self.argv[0].readString());
launch_stun(argc, argv );
break;
case 'stop':
self.postMessage('WORKER STOPPED: ' + data.msg +
'. (buttons will no longer work)');
self.close(); // Terminates the worker.
break;
default:
self.postMessage('Unknown command: ' + data.msg);
};
}, false);
"Message 2" is never printed to the screen, and "Message 1" is. It's almost like I am getting a silent fail from one of those other lines, but this is the exact code I have used to launch this from main.js, before I tried to use ChromeWorker.
Any ideas? I guess it seems like stun-manager.js is failing silently, and on a related note, I can't even find it in the Browser Toolbox to debug, but I do see my main.js file there.
Two simple examples of using ChromeWorker (and also an advancement of ChromeWorker, PromiseWorker, which rocks by the way):
GitHub :: Noitidart / ChromeWorker
GitHub :: Noitidart / PromiseWorker
You can't do var {ctypes} = Cu.import("resource://gre/modules/ctypes.jsm") in the worker (your worker is stun-manager.js). That's causing an error, remove that. You can just use ctypes without importing anything, ChromeWorker's autoamtically have it. That should fix it.
I'll look more over your code, but definitely check out the ChromeWorker repo it will help a lot, its a very basic messaging thing between worker and main.

Script Works on Win 7, Not on Server 2003

I have a script that is rather simple, it boots up WinSCP and checks the directory for a file that starts with "TSA". If the file exists, it exits, if it does not exist, it transfers over a new file.
Its up and running on my Windows 7 machine, that is where i created it - but when i transfer it over to my server [windows server 2003] it never finds the file.
My script:
var FILEPATH = "../zfinance/TSA";
// Session to connect to
var SESSION = "someplace#somewhere.com";
// Path to winscp.com
var WINSCP = "c:\\program files\\winscp\\winscp.com";
var filesys = WScript.CreateObject("Scripting.FileSystemObject");
var shell = WScript.CreateObject("WScript.Shell");
var logfilepath = filesys.GetSpecialFolder(2) + "\\" + filesys.GetTempName() + ".xml";
var p = FILEPATH.lastIndexOf('/');
var path = FILEPATH.substring(0, p);
var filename = FILEPATH.substring(p + 1);
var exec;
// run winscp to check for file existence
exec = shell.Exec("\"" + WINSCP + "\" /log=\"" + logfilepath + "\"");
exec.StdIn.Write(
"option batch abort\n" +
"open \"" + SESSION + "\"\n" +
"ls \"" + path + "\"\n" +
"exit\n");
// wait until the script finishes
while (exec.Status == 0)
{
WScript.Sleep(100);
WScript.Echo(exec.StdOut.ReadAll());
}
if (exec.ExitCode != 0)
{
WScript.Echo("Error checking for file existence");
WScript.Quit(1);
}
// look for log file
var logfile = filesys.GetFile(logfilepath);
if (logfile == null)
{
WScript.Echo("Cannot find log file");
WScript.Quit(1);
}
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
doc.setProperty("SelectionLanguage", "XPath");
var nodes = doc.selectNodes("//w:file/w:filename[starts-with(#value, '" + filename + "')]");
if (nodes.length > 0)
{
WScript.Echo("File found");
WScript.Quit(0);
}
else
{
WScript.Echo("File not found");
WScript.Quit(1);
}
After much investigation, i think i've found the piece of code that does not function properly:
// parse XML log file
var doc = new ActiveXObject("MSXML2.DOMDocument.6.0");
doc.async = false;
doc.load(logfilepath);
doc.setProperty("SelectionNamespaces",
"xmlns:w='http://winscp.net/schema/session/1.0'");
The only problem is, i have no idea why. The log file at this point should be written over with the xml code, but this does not happen.
Thanks in advance for any help.
And the answer is........... WinSCP on Windows Server 2003 was WAY out of date. So out of date that the log was completely different from one version to the next. Updated and VIOLA! Problem solved. Thanks for your help.
Maybe you need to install MSXML2.DOMDocument.6.0
http://msdn.microsoft.com/en-us/library/windows/desktop/cc507436%28v=vs.85%29.aspx
If you open up regedit and look for "MSXML2.DOMDocument.6.0" does it find it? If so maybe security settings for the script need to be set in order to be able to create an activeX object.
What can you see when you put some stuff in try catch?
try{
//stuff
}catch(e){
WScript.Echo(e.message);
}

Resources