How can i send a Pagination-embed with a music list discord.js - list

I want send in a Pagination-embed with a music list because whan an embed is lower at 1024 letters it doesn't send.
I want send in many pages (4musics max per pages)
Sorry for my english, i'm french...
console.log(_serverQueue.songs)
let q = ``;
for(var i = 1; i < _serverQueue.songs.length; i++) {
q += `\n${i + 1}. **${_serverQueue.songs[i].title}**`;
}
let resp = [
{name: `Now Playing`, value: _serverQueue.songs[0].title},
{name: `Queue`, value: q},
];
//Putting it all together
const FieldsEmbed = new Pagination.FieldsEmbed()
.setArray({word: `Queue`})
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setElementsPerPage(4)
.setPageIndicator(true)
.formatField('Playlist :', el => el.word)
FieldsEmbed.embed
.setColor('#008000')
.setTitle('Playlist :')
FieldsEmbed.build()
}

As per the Documentation of https://www.npmjs.com/package/discord-paginationembed
I explained the steps with Comments
const Discord = require('discord.js');
const Pagination = require('discord-paginationembed');
const songText = ["This is a long SongText", "That is Split up Over", "Multiple Sites", "End of Song"];
// The Splitting can happen via Discord.Js Util Class, it has a Splitter
const embeds = [];
for (let i = 1; i <= 4; ++i)
embeds.push(new Discord.MessageEmbed().setFooter('Page ' + i).setDescription(songText[i - 1]));
// Create Embeds here with the Content and push them into the Array
const myImage = message.author.displayAvatarURL();
new Pagination.Embeds()
.setArray(embeds)
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setPageIndicator(true)
.setPage(1)
// Methods below are for customizing all embeds
.setImage(myImage)
.setThumbnail(myImage)
.setTitle('Test Title')
.setDescription('Test Description')
.setURL(myImage)
.setColor(0xFF00AE)
.build();

Related

Copying certain rows to duplicated sheet using macro

I've got a google sheet which I'm using as a monthly handover sheet with a to-do list at the bottom.
The to-do list has a checkbox then a couple of columns of information (a date, the task and who it's assigned to)
To-Do List
I've created a button that runs a macro to duplicate the sheet to create a copied sheet at the end of the month.
I'd like to copy over any tasks in the to-do list which haven't been 'ticked' as completed but I'm not very good at logic in google apps script.
Could anyone help me write the if statement to either copy unticked rows to the duplicated sheet or do duplicate all rows then delete the ticked ones.
Thanks, Joe
UPDATE: after playing around for a couple of hours, this is what I've got:
function ToDoCopy() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var duplicateSheet = ss.getSheetByName("JUNE");
var originalSheet = ss.getSheetByName("MAY");
var lastRow = originalSheet.getLastRow() + 1;
for(var j = 24; j < lastRow; j++)
{
if(originalSheet.getRange(j,2).getValue() ==false && originalSheet.getRange(j,3).getValue() != 4)
{
var nextRow = duplicateSheet.getLastRow() +1;
var getCopyRange = originalSheet.getRange('B' + j + ':P' + j);
getCopyRange.copyTo(duplicateSheet.getRange(nextRow, 2));
}
}
}
It's almost working but it adds the copied items underneath the to-do table on the new sheet rather than adding them to the top. I can't work out how to fix this!
(p.s. the && originalSheet.getRange(j,3).getValue() != 4 part is a hidden row which I use for auto-sorting the table, '4' means it's empty basically.
function ToDoCopy() {
const ss = SpreadsheetApp.getActive();
const ssh = ss.getSheetByName("MAY");//source sheet
const sshsr = 24;//start row
const srg = ssh.getRange(sshsr, 1, ssh.getLastRow() - sshsr + 1, ssh.getLastColumn());
const svs = srg.getDisplayValues();//useful for me when using checkboxes
const dsh = ss.getSheetByName("JUNE");//destination sheet
if (dsh.getLastRow() - sshsr + 1 > 0) {
dsh.getRange(sshsr, 1, dsh.getLastRow() - sshsr + 1, dsh.getLastColumn()).clearContent().setDataValidation(null);//Clear destination range if not already cleared
}
let a = 0;//row add counter
svs.forEach((r, i) => {
if (r[1] == 'FALSE' && r[2] != 4) {
ssh.getRange(sshsr + i, 1, 1, ssh.getLastColumn()).copyTo(dsh.getRange(sshsr + a++, 1));
}
});
}

Getting EntityTooSmall Exception

I am trying to download data from Azure blob in chunk and then trying to upload same chunk to aws s3 bucket.
While uploading I am getting "Your proposed upload is smaller than the minimum allowed size"exception. One thing I noticed, in upload response I am getting 0 content length. Data size I am trying is more than 300MB.
Any pointers what could be wrong here?
Below is my code snippet :
var remainingLength = blob.Properties.Length;
long startPosition = 0;
List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();
int i = 1;
string uploadId = string.Empty;
//Step 1: build and send a multi upload request
var initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = existingBucketName,
Key = "firstobj"
};
var initResponse = client.InitiateMultipartUpload(initiateRequest);
uploadId = initResponse.UploadId;
do
{
var blockSize = Math.Min(segmentSize, remainingLength);
using (var ms = new MemoryStream())
{
blob.DownloadRangeToStream(ms, startPosition, blockSize);
//Step 2: upload each chunk (this is run for every chunk unlike the other steps which are run once)
var uploadRequest = new UploadPartRequest
{
BucketName = existingBucketName,
Key = "firstobj",
UploadId = uploadId,
PartNumber = i,
PartSize = ms.Length,
InputStream = ms
};
// Upload part and add response to our list.
var temp = client.UploadPart(uploadRequest);
uploadResponses.Add(temp);
}
//Step 3: build and send the multipart complete request
if (blockSize < segmentSize)
{
var completeRequest = new CompleteMultipartUploadRequest
{
BucketName = existingBucketName,
Key = "firstobj",
UploadId = uploadId,
};
completeRequest.AddPartETags(uploadResponses);
client.CompleteMultipartUpload(completeRequest);
}
startPosition += blockSize;
remainingLength -= blockSize;
i++;
}
while (remainingLength > 0);
After banging my head a lot, I got solution for this. It was in step 2 just before uploading part to AWS we should set stream position to 0.
uploadRequest.InputStream.Position = 0;

Gmail App search criteria

I have the following search criteria working very well in Gmail:
user#domain from:/mail delivery/ || /postmaster/ ||/Undeliverable/
I am trying to write Goole Apps code to return the same results. Here is the code:
var thread=GmailApp.search("user#domain from:/mail delivery/ || /postmaster/ ||/Undeliverable/ ");
I am getting different results. I am new to both Regex and Google Apps.
Try Amit Agarwal's tutorial on Gmail Search with Google Apps Script which includes Using Regular Expressions to Find Anything in your Gmail Mailbox:
function Search() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = 2;
// Clear existing search results
sheet.getRange(2, 1, sheet.getMaxRows() - 1, 4).clearContent();
// Which Gmail Label should be searched?
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Format and print the date of the matching message
sheet.getRange(row,1).setValue(
Utilities.formatDate(messages[m].getDate(),"GMT","yyyy-MM-dd"));
// Print the sender's name and email address
sheet.getRange(row,2).setValue(messages[m].getFrom());
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getSubject());
// Print the unique URL of the Gmail message
var id = "https://mail.google.com/mail/u/0/#all/"
+ messages[m].getId();
sheet.getRange(row,4).setFormula(
'=hyperlink("' + id + '", "View")');
// Move to the next row
row++;
}
}
}
}

Extracting mails from a spreadsheet

I have a Google Spreadsheet with two columns.
First column includes the name of a referrer and second column includes a free format text where some referred email addresses are mentioned. There might be multiple email addresses in one cell, or none.
Ex:
Referrer | Referral
--------------------------------------------------------------------------
Mister X | I would like to refer somebody#gmail.com and somebodyelse#outlook.com
Miss Y | myfriend#mail.com
Mister Z | None!
etc | ...
I would like to format the data such that for each referred address we have the referrer and the email address referred.
EX:
Referrer | Referral
--------------------------------------------------------------------------
Mister X | somebody#gmail.com
Mister X | somebodyelse#outlook.com
Miss Y | myfriend#mail.com
etc | ...
What is the best way of achieving this?
Here's your original data in a table.
Referrer Referral
Mister X I would like to refer somebody#gmail.com and somebodyelse#outlook.com
Miss Y myfriend#mail.com
Mister Z None!
Here's the same columns after they're over written.
Referrer none
Mister X somebody#gmail.com
Mister X somebodyelse#outlook.com
Miss Y myfriend#mail.com
Mister Z none
And here's the code. Currently, you select the two columns as we were shown and I over write them in the format your requested. Although with such a limited dataset one can never be 100% sure. So further testing would be good. I included the menu and some of my display routines which help me debug the program. I suppose you may want to change the range. Go for it. Have fun. I enjoyed writing it.
function onOpen()
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Tools')
.addItem('Extract Emails','emailFishing')
.addToUi();
}
function emailFishing()
{
var rng = SpreadsheetApp.getActiveRange();
var rngA = rng.getValues();
var resultsA = [];
//var s = '[';
for(var i = 0;i < rngA.length; i++)
{
if(rngA[i][1])
{
matchA = extractEmails(rngA[i][1]);
if(matchA)
{
for(var j = 0; j < matchA.length;j++)
{
resultsA.push([rngA[i][0], matchA[j]]);
//s += '[' + rngA[i][0] + ', ' + matchA[j] + '], '
}
}
else
{
resultsA.push([rngA[i][0],'none']);
//s += '[' + rngA[i][0] + ', \'none\'],'
}
}
}
//s += ']';
var orng = SpreadsheetApp.getActiveSheet().getRange(rng.getRow(), rng.getColumn(), resultsA.length, resultsA[0].length);
orng.setValues(resultsA);
//dispStatus('Results Array', s, 500, 400);
}
function extractEmails (text)
{
return text.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
function dispStatus(title,html,width,height)
{
// Display a modeless dialog box with custom HtmlService content.
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 250;
var height = typeof(height) !== 'undefined' ? height : 300;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
The function extractEmail came from Leniel Macaferi. From this post Extract all email addresses from bulk text using jquery. Although I left out the JQuery part.

JSON.parse error on simplejson return in Django

I have a view page that currently has two columns of data shown, soon to be expanded to four. Each column contains the result of a QuerySet for that particular model.
Here's what I have in my views.py method:
if request.REQUEST["type"] == "text":
client = Client.objects.get(client_name = request.REQUEST["search"])
peerList = ClientPeers.objects.prefetch_related().filter(client = client.client)
compList = ClientCompetitors.objects.prefetch_related().filter(client = client.client)
else:
peerList = ClientPeers.objects.prefetch_related().filter(client = request.REQUEST["search"])
compList = ClientCompetitors.objects.prefetch_related().filter(client = request.REQUEST["search"])
for peer in peerList:
peerlst.append({"pid" : peer.parentorg.parentorg, "pname" : peer.parentorg.parentorgname})
for comp in compList:
complst.append({"cid" : comp.parentorg.parentorg, "cname" : comp.parentorg.parentorgname})
lst.append(simplejson.dumps(peerlst))
lst.append(simplejson.dumps(complst))
return HttpResponse(simplejson.dumps(lst), mimetype = "text/json")
This allows me to send a 2D array of data to the browser in the format
[ { //JSON }, { //JSON } ]
In my jQuery.ajax success function, I have
function handler(results) {
var data = JSON.parse(results);
for (var i = 0; i < data[0].length; i++)
$("#available_peers").append("<li>" + data[0][i].pname + "</li>");
for (var i = 0; i < data[1].length; i++)
$("#available_competitors").append("<li>" + data[1][i].cname + "</li>");
Firebug shows that the GET request works and I can see the data in the response tab. However, the console prints out
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
var data = JSON.parse(results)
This error disappears if I replace var data = JSON.parse(results) with
var peers = JSON.parse(data[0]);
var comps = JSON.parse(data[1]);
Why does one method work but another doesn't?
The jQuery ajax() call will make an intelligent guess as to the returned data type. In your example, function handler(results), the results variable will already be a decoded JSON object, containing two items in an array. The reason that JSON.parse(data[0]) works, is that you have returned JSON encoded data as a string.
Don't encode the individual list elements to JSON before placing in the output array:
lst.append(peerlst) # <-- Don't encode to JSON string here
lst.append(complst)
return HttpResponse(simplejson.dumps(lst), mimetype = "application/json") # <-- Single JSON encoding