i am using a mish mash of scripts as i do not know coding to be honest, and its working for the most part, but i am struggling with stop, help and cancel during the welcome speech, stop/cancel works ok once you get to the next part, but during the welcome speech, exanmples
User: "Alexa open breckland weather"
Skill: "Welcome to Breckland Weather. Please ask me for the weather, heres a hint, whats the weather like or whats the current conditions."
User: "stop" / User: "cancel" / User: "help"
Skill: "There was a problem with the requested skill's response"
The intents are there and i added utterances in case but still the same so i feel theres sommat in the code thats not right, probably most of it lol, please can one of you kind soles peruse at your leisure and see if you can shed a little light?
exports.handler = (event, context, callback) => {
try {
//console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);
//if (event.session.application.applicationId !== APP_ID) {
// callback('Invalid Application ID');
//}
if (event.session.new) {
onSessionStarted({ requestId: event.request.requestId }, event.session);
}
if (event.request.type === 'LaunchRequest') {
onLaunch(event.request,
event.session, (sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'IntentRequest') {
onIntent(event.request,
event.session,
(sessionAttributes, speechletResponse) => {
callback(null, buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === 'SessionEndedRequest') {
onSessionEnded(event.request, event.session);
callback();
}
} catch (err) {
callback(err);
}
};
const isDebug = false;
const APP_ID = 'amzn1.ask.skill.d31840b5-27f2-4f07-9e19-ec0c73d78b39';
const url_weather = 'http://www.brecklandweather.com/currentout.txt';
const APP_NAME = 'Breckland Weather';
const STR_REPROMPT = '\nPlease ask me for the weather, heres a hint, whats the weather like or whats the current conditions.';
const HELP_MESSAGE = 'You can say whats the weather like, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
function getWeather(intent, session, callback, numLetters) {
let speechOutput = '';
let cardTitle = 'Weather output';
getWebRequest(url_weather, function webResonseCallback(err, data) {
if (err) {
speechOutput = `DOH! somethings done gone bad, self destuct in 3 2 ah, false alarm, still broken though, carry on.`;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, STR_REPROMPT));
} else {
//if (isDebug) {"SolveAnagram::data = " + console.log(data)};
speechOutput = data;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, STR_REPROMPT));
}
});
}
//Simple welcome intent handler
function getWelcomeResponse(callback) {
console.log("START session");
if (isDebug) {console.log("getWelcomeResponse()")}
const cardTitle = APP_NAME;
const speechOutput = 'Welcome to '+APP_NAME+'. '+ STR_REPROMPT;
// If the user either does not reply to the welcome message or says something that is not
// understood, they will be prompted again with this text.
const repromptText = STR_REPROMPT;
const shouldEndSession = false;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
//My effort of code
const handlers = {
'LaunchRequest': function () {
// this.emit('myIntent');
this.emit(':tell', '2 Hello, what would you like to do?');
},
'AMAZON.HelpIntent': function () {
const speechOutput = HELP_MESSAGE;
const reprompt = HELP_REPROMPT;
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
},
'AMAZON.CancelIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
this.response.speak(STOP_MESSAGE);
this.emit(':responseReady');
},
};
//Simple end session intent handler
function handleSessionEndRequest(callback) {
console.log("END session");
const cardTitle = 'Goodbye';
const speechOutput = 'Thanks for using '+APP_NAME+'.';
const shouldEndSession = false;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
if (isDebug) {console.log(`buildSpeechletResponse(title:${title}, shouldEndSession:${shouldEndSession}, reprompt:${repromptText})`)}
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `${title}`,
content: `${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '2.0',
response: speechletResponse,
sessionAttributes: sessionAttributes,
};
}
//----------------- Web service helper ----------------------//
var http = require('http');
function getWebRequest(url,doWebRequestCallBack) {
try
{
http.get(url, function (res) {
var webResponseString = '';
if (isDebug) {console.log('Status Code: ' + res.statusCode)}
if (res.statusCode != 200) {
doWebRequestCallBack(new Error("Non 200 Response"));
return;
}
res.on('data', function (data) {
webResponseString += data;
});
res.on('end', function () {
//if (isDebug) {console.log('getWebRequest::Got some data: '+ webResponseString)};
//the weather isn't JSON so just return the string
//var webResponseObject = JSON.parse(webResponseString);
doWebRequestCallBack(null, webResponseString);
});
}).on('error', function (e) {
if (isDebug) {console.log("Communications error: " + e.message)}
doWebRequestCallBack(new Error(e.message));
});
}
catch(err)
{
doWebRequestCallBack(new Error(err.message));
}
}
// --------------- Events -----------------------
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
//console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}
/**
* Called when the user launches the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
//console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);
// Dispatch to your skill's launch.
getWelcomeResponse(callback);
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
console.log(" ");
console.log("== New Intent ==");
console.log(`onIntent(${intentName})`);
if (intentName === 'GetWeather') {
getWeather(intent, session, callback,1);
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
//console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
// Add cleanup logic here
}
Your design pattern is quite confusing. But I see where your problem is. You are not using your handlers object for handling intent requests at all. According to your design pattern you can make changes as follows:
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
const intent = intentRequest.intent;
const intentName = intentRequest.intent.name;
console.log(" ");
console.log("== New Intent ==");
console.log(`onIntent(${intentName})`);
if (intentName === 'GetWeather') {
getWeather(intent, session, callback,1);
}else if(intentName === 'AMAZON.StopIntent'){
getStopResponse(intent, session, callback,1)
}else if(intentName === 'AMAZON.HelpIntent'){
getHelpResponse(intent, session, callback,1)
}
}
And response builder function as follows:
//Simple welcome intent handler
function getStopResponse(callback) {
console.log("START session");
if (isDebug) {console.log("getStopResponse()")}
const cardTitle = APP_NAME;
const speechOutput = STOP_MESSAGE
const repromptText = STOP_MESSAGE;
const shouldEndSession = true;
callback({}, buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
Similar one would go for getHelpResponse(). I will leave that up to you.
Tell me if this helps you.
Related
Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?
I am working on a music and I would like to know how to add a queue system to the command; I have been looking around for hours and not been able to find anything on it,
If anyone can help that would be great and I don't need a queue command but I do need to add a queue system so it would really help I will be checking back in an hour to see if anyone has given me or an idea or the answer to my problem
This is my code so far:
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const YoutubeSearcher = new QuickYtSearch({
YtApiKey: '',
});
module.exports={
name: 'play',
category: 'music',
description: 'Joins and plays the song',
aliases: ['p'],
usage: '.play <song name or URL>',
run: async(client, message, args)=>{
try{
if (message.member.voice.channel) {
let args = message.content.split(' ').slice(1).join(' ');
if (!args) {
const error = new Discord.MessageEmbed()
.setTitle(`🔴 Looks like there is an Issue!`)
.setColor(0x2f3136)
.setDescription(`You have to provide me at least, the name or the url.\n\nExample :
\`\`\`fix
.play <url>
OR
.play <name>\`\`\``)
return message.channel.send(error);
};
message.member.voice.channel.join()
.then(connection => {
if (YoutubeSearcher.isVideoUrl(args) === false) {
YoutubeSearcher.getVideo(args).then(video => {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(video.url, { filter: 'audioonly' }, volume));
const play1 = new Discord.MessageEmbed()
.setTitle('Song info')
.setURL(video.url)
.setDescription(`Name: ${video.title}, By: ${video.channelTitle}`)
.setThumbnail(video.highThumbnail)
message.channel.send(play1);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.');
message.member.guild.me.voice.channel.leave();
});
});
} else {
const volume = { volume: 10 };
const dispatcher = connection.play(ytdl(args, { filter: 'audioonly' }, volume));
message.reply('Now playing ' + args);
dispatcher.on("finish", () => {
dispatcher.end();
message.reply('End of the song.')
message.member.guild.me.voice.channel.leave();
});
};
});
} else {
message.reply('You need to join a voice channel.');
};
}catch(err) {
console.log(err)
return message.channel.send(`Error: ${err.message}`)
}
}
}
In theory you could use the queue data structure (the last element is taken out and when a new one is added it is added to the start) and in the queue hold the music that is requested to be played. This is how it might roughly look like:
client.on("message", (msg) => {
var arrOfMusic = [];
if(msg.content.startsWith("!queue")){
msg.channel.send(arrOfMusic.join(" , ")
}
if(msg.content.startsWith("!play")){
arrOfMusic.push(msg.content.slice(6))
// you don't need to play the music
}
// your code to play the end of the array all you do is play the last element you also //need to check once it is over and use pop to remove last element
if(msg.content.startsWith("clear")){
arrOfMusic = []
}
})
I have drift's async script code in the index.html file of the react app.
<script>
"use strict";
!function () {
var t = window.driftt = window.drift = window.driftt || [];
if (!t.init) {
if (t.invoked) return void (window.console && console.error && console.error("Drift snippet included twice."));
t.invoked = !0, t.methods = ["identify", "config", "track", "reset", "debug", "show", "ping", "page", "hide", "off", "on"],
t.factory = function (e) {
return function () {
var n = Array.prototype.slice.call(arguments);
return n.unshift(e), t.push(n), t;
};
}, t.methods.forEach(function (e) {
t[e] = t.factory(e);
}), t.load = function (t) {
var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement("script");
o.type = "text/javascript", o.async = !0, o.crossorigin = "anonymous", o.src = "https://js.driftt.com/include/" + n + "/" + t + ".js";
var i = document.getElementsByTagName("script")[0];
i.parentNode.insertBefore(o, i);
};
}
}();
drift.SNIPPET_VERSION = '0.3.1';
drift.load('----api----');
drift.on('ready', api => {
api.widget.hide();
})
</script>
The issue is, it is getting popped up in every page of the app whereas I want it only when I click a button(onClick)
The function to trigger onClick :
openDriftChat = () =>{
const { setDriftState } = this.props;
if (window.drift.api) {
//this needs to happen only once but currently happening on every page load
if (!this.props.driftInit) {
if (localStorage.token) {
var tokenBase64 = localStorage.token.split(".")[1];
var tokenBase64_1 = tokenBase64.replace("-", "+").replace("_", "/");
var token = JSON.parse(window.atob(tokenBase64_1));
window.drift.identify(token.email, {
email: token.email,
nickname: token.name
});
setDriftState(true);
}
}
window.drift.api.openChat();
}
}
I basically want it pop up only when I call the function.
Hello I had the same issue:
To hide the welcome message use the following css code
iframe#drift-widget.drift-widget-welcome-expanded-online {
display: none !important;
}
iframe#drift-widget.drift-widget-welcome-expanded-away {
display: none !important;
}
The welcome message will only be shown when your drift button. Some extra info:
To hide the drift button icon use the following js code
drift.on('ready', function (api) {
api.widget.hide()
drift.on('message', function (e) {
if (!e.data.sidebarOpen) {
api.widget.show()
}
})
drift.on('sidebarClose', function (e) {
if (e.data.widgetVisible) {
api.widget.hide()
}
})
})
To call for the sidebar from a specific button use the following
Javascript
(function () {
var DRIFT_CHAT_SELECTOR = '.drift-open-chat'
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function () {
if (document.readyState != 'loading')
fn();
});
}
}
function forEachElement(selector, fn) {
var elements = document.querySelectorAll(selector);
for (var i = 0; i < elements.length; i++)
fn(elements[i], i);
}
function openSidebar(driftApi, event) {
event.preventDefault();
driftApi.sidebar.open();
return false;
}
ready(function () {
drift.on('ready', function (api) {
var handleClick = openSidebar.bind(this, api)
forEachElement(DRIFT_CHAT_SELECTOR, function (el) {
el.addEventListener('click', handleClick);
});
});
});
})();
HTML
<a class="drift-open-chat">Open Chat</a>
I hope this helps someone out there.
PS: The above javascript code must be included after you have initialized your drift widget.
You need to disable that through the application: turn off the Playbooks.
Here is the link to do so: https://app.drift.com/playbooks
Hope it helps.
I've been working on a discord bot for a little while now, and just started to code up the play command for music. I've encountered an issue where it states: 'PlayCommand' is declared but never used. What should I do to fix it?
I've tried moving the line closer to the top and it then declares it, but messes up my other code.
const YTDL = require('ytdl-core');
function Play(connection, message)
{
var server = servers[message.guild.id];
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0])
{
Play(connection,message);
}
else
{
connection.disconnect();
}
});
//Here
class PlayCommand extends Commando.Command
//Here
{
constructor(client)
{
super(client,{
name: 'play',
group: 'music',
memberName: 'play',
description: 'Adds a song to the queue',
});
}
async run(message, args)
{
if(message.member.voiceChannel)
{
if(!message.guild.voiceConnection)
{
if(!servers[message.guild.id])
{
servers[message.guild.id] = {queue: []}
}
var server = server [message.guild.id];
server.queue.push(args);
Play(connection, message);
}
}
}
}
}
module.exports = PlayCommand;
I expect it to declare the value is read, as on the other commands it has declared it.
This is library I use.
For rebuilding playlist I do following:
angularPlayer.clearPlaylist(function () {
angular.forEach($scope.filtered, function (value) {
//$scope.$apply(function () {
angularPlayer.addTrack(value);
//});
});
});
Firstly, I clear playlist by function angularPlayer.clearPlaylist.
After I add all tracks in loop using angularPlayer.addTrack.
At the end I try to play playlist:
angularPlayer.play();
But it does now work. I checked console Chrome there are not errors.
I tried some ways and have invite solution, may be it will be useful for someone:
$scope.play = function (genre) {
$timeout(function () {
angularPlayer.stop();
angularPlayer.setCurrentTrack(null);
angularPlayer.clearPlaylist(function () {
if (genre !== undefined) {
$scope.filtered = filterFilter($scope.songs, {'genre': genre});
} else {
$scope.filtered = $scope.songs;
}
if (random) {
$scope.filtered = $filter('shuffleArray')($scope.filtered);
}
if ($scope.filtered.length == 0) {
console.log("No songs by genre " + genre);
}
angular.forEach($scope.filtered, function (value) {
angularPlayer.addTrack(value);
});
angularPlayer.play();
});
});
};