I am trying to run my game inside telegram in-app browser.
Below are my code so far
bot.action('wheeloffortune', ctx => {
bot.telegram.sendGame(ctx.chat.id, 'wheeloffortune');
})
bot.on("callback_query", function (query) {
let gameurl = "https://dazzling-ritchie-f3ad20.netlify.app/?id="+query.id;
bot.answerCallbackQuery({
callback_query_id: query.id,
url: gameurl
});
});
bot.on("inline_query", function(iq) {
bot.answerInlineQuery(iq.id, [ { type: "game", id: "0", game_short_name: 'wheeloffortune' } ] );
});
What I expect: after clicking the button 'Play wheeloffortune', the game should open in webview.
What is actually happening:
this image keep rendering
any advice is appreciated
According to the game example of telegraf:
You can simply use:
bot.gameQuery((ctx) => {
let queryId = ctx.callbackQuery.id
let gameurl = "https://dazzling-ritchie-f3ad20.netlify.app/?id="+queryId;
ctx.answerGameQuery(gameUrl)
})
Related
What i want to load a custom .wsz skin on page-load on my website.
I still don't understand how to do it to make it work.
Here a snippet with my code:
https://codepen.io/cat999/pen/rNOOjJP
js
const webamp = new Webamp({
initialTracks: [{
metaData: {
artist: "DJ Mike Llama",
title: "Llama Whippin' Intro",
},
url: "https://cdn.rawgit.com/captbaritone/webamp/43434d82/mp3/llama-2.91.mp3",
duration: 5.322286,
}],
})
webamp.onMinimize(() => {
const webampEl = document.getElementById('webamp')
webampEl.style.display = 'none'
})
webamp.renderWhenReady(document.getElementById('app')).then(() => {
document.getElementById('close').addEventListener('click', (e) => {
e.stopPropagation()
const webampEl = document.getElementById('webamp')
webampEl.style.display = 'none'
})
document.getElementById('open').addEventListener('click', () => {
const webampEl = document.getElementById('webamp')
webampEl.style.display = 'block'
})
})
Here below the skins I would like to see on my page-load
https://srv-file6.gofile.io/download/KwUySB/Aphex_Twin_-_Windowlicker.wsz
Anyone could help on How I should improve my js code to make It work?
Have you seen the Initialization portion of the docs?
https://github.com/captbaritone/webamp/blob/master/docs/usage.md#initialize-the-javascript
Try constructing Webamp by adding an initialSkin option:
const webamp = new Webamp({
initialTracks: [{
metaData: {
artist: "DJ Mike Llama",
title: "Llama Whippin' Intro",
},
url: "https://cdn.rawgit.com/captbaritone/webamp/43434d82/mp3/llama-2.91.mp3",
duration: 5.322286,
}],
initialSkin: {
url: "https://s3.amazonaws.com/webamp-uploaded-skins/skins/dbaead7a819b238d48ca726abd0617bb.wsz"
},
})
I have an object here in a file called audio.js:
const audio = {
controls: true,
source: [
{
src: 'https://testname.com/Track03.mp3',
type: 'audio/mpeg'
},
{
src: 'https://testname.com/Track03.ogg',
type: 'audio/ogg'
}
]
};
I've included the audio.js file, but am completely lost on how to render these two audio players into my website, using a loop probably.
All I've managed to get done so far is this, which is evidently incomplete, and would like to expand on it if possible.
<div id="audio">
<script>
let audioo = document.createElement('audio');
</script>
</div>
Sorry, I'm new to all of this and can't find any reliable information. Any help would be appreciated.
Here is a way you can generate them dynamically by javascript; and you don't need to put this string inside <div id='audio'></div> to work, you can use it any where in your javascript.
const audio = {
controls: true,
source: [
{
src: 'https://testname.com/Track03.mp3',
type: 'audio/mpeg'
},
{
src: 'https://testname.com/Track03.ogg',
type: 'audio/ogg'
}
]
}
const theDiv = document.querySelector("#audio");
audio.source.forEach(as=>{
let newAudioElement = document.createElement('audio');
newAudioElement.src = as.src;
newAudioElement.type = as.type;
newAudioElement.controls = 'controls';
theDiv.appendChild(newAudioElement);
})
Here is a working example:
// replacing some working audio urls
const audio = {
controls: true,
source: [
{
src: 'https://www.w3schools.com/tags/horse.mp3',
type: 'audio/mp3'
},
{
src: 'https://www.w3schools.com/tags/horse.ogg',
type: 'audio/ogg'
}
]
}
const theDiv = document.querySelector("#audio");
audio.source.forEach(as=>{
let newAudioElement = document.createElement('audio');
newAudioElement.src = as.src;
newAudioElement.type = as.type;
newAudioElement.controls = 'controls';
theDiv.appendChild(newAudioElement);
})
<div id="audio"></div>
I'm developing a chat bot (v4 using MS Azure bot framework & QnAmaker),
I've added a feature in that, i.e. while the users starts typing the questions, the bot will get prompt and show the relevant questions form the QnAmaker , and the user can select one of them , then that particular question will sent to the bot.
Following is the full code which I'm using,
<html>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const styleOptions = {
hideUploadButton: true,
bubbleBackground: '#D8F4FF',
bubbleFromUserBackground: '#E8E8E8',
botAvatarImage: '../botavatar.PNG',
botAvatarInitials: 'bot',
userAvatarInitials: initial,
userAvatarImage: userimg,
rootHeight: '100%',
rootWidth: '50%'
};
const styleSet = window.WebChat.createStyleSet({
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
});
styleSet.textContent = {
fontFamily: "'Comic Sans MS', 'Arial', sans-serif",
fontWeight: 'bold'
};
const secret = secret;
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate',
{
headers: {
Authorization: `Bearer ${secret}`,
},
method: 'POST'
});
const { token } = await res.json();
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
}
});
}
return next(action);
}
);
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store,
styleOptions,
userID: emailid,
username: fullname,
locale: 'en-US',
userAvatarInitials: initial
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
document.querySelectorAll('[aria-label="Sendbox"]')[0].placeholder = "Type your question and press enter";
$("[aria-label='Sendbox']").keypress(function () {
if ($("[aria-label='Sendbox']")[0].defaultValue.length > 4) {
getquestion(this.value);
} else {
$('#ques').remove();
}
});
$('div.probing').click(function () { alert(this.innerText); });
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
})().catch(err => console.error(err));
function getquestion(value) {
var token = secret;
var questionquery =
{
question: value,
top: 2,
scoreThreshold: 50,
"strictFilters": [
{
"name": "message",
"value": "text"
}],
}
$.ajax({
type: "POST",
url: "https://endpoint/qnamaker/knowledgebases/KBID/generateAnswer",
data: JSON.stringify(questionquery),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', secret);
},
dataType: "json",
contentType: "application/json",
success: function (data) {
var questions = "";
$('#ques').remove();
for (var i = 0; i < 4; i++) {
if (data.answers[0].questions[i] != null && data.answers[0].questions[i] != 'undefined')
questions = questions + "<div class='probing'>" + data.answers[0].questions[i] + "</div>";
}
$('.content').last().append("<div id='ques'>" + questions + "</div>");
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
},
error: function (data) {
alert(data.responseText);
}
});
}
</script>
</body>
</html>
Please check the below image of my bot with the prompted questions, it will look like this, these questions are get appended to the last reply given by the bot, after selecting the question, this div will get removed. On the next question this cycle will continue again.
Problem I'm facing is here, with the following code the value is getting entered in the input box, however the bot does not received any question, and hence it failed to answer.
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
With this code the value is getting entered in the input box, however the bot does not received any question, and hence it failed to answer.
this is how it will in console after adding the question by script.
Note that I've used all the required reference JS and CSS Files in my code.
So please help me with the correct approach to achieve my requirement, Thanks in Advance.
Here's a working demo that should get you started, using a similar method from the sample:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Programmatic access to post activity</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to pointing to Web Chat's MyGet feed:
https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
-->
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// Your client code must provide either a secret or a token to talk to your bot.
// Tokens are more secure. To learn about the differences between secrets and tokens
// and to understand the risks associated with using secrets, visit https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
// We are creating the Web Chat store here so we can dispatch WEB_CHAT/SEND_MESSAGE action later.
const store = window.WebChat.createStore();
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token: '<your token>' }),
// We are passing our own version of Web Chat store.
store
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
// THIS IS THE IMPORTANT STUFF
const sendbox = document.querySelector("[aria-label='Sendbox']");
function removeQuestions() {
const questionDivs = document.querySelectorAll('.questions');
questionDivs.forEach((div) => {
div.remove();
})
}
// This ensures that we create unique listeners for each question
let totalQuestions = 0;
// Track the keypress events in the Send Box
sendbox.addEventListener('keypress', () => {
if (sendbox.defaultValue.length > 4) {
getQuestion();
} else {
removeQuestions();
}
});
// Send a message containing the innerText of the target element
function send(event) {
store.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: { text: event.currentTarget.innerText }
});
event.currentTarget.remove();
}
// This generates some test questions
function getQuestion() {
// Create questions div
const questions = document.createElement('DIV');
questions.setAttribute('class', 'questions');
document.querySelector('.content').appendChild(questions);
// Generate test questions
for (var i = 0; i < 4; i++) {
// Create question div
const question = document.createElement('DIV');
question.setAttribute('id', `question${totalQuestions}`);
question.setAttribute('class', 'probing');
question.innerText = `this is a test ${totalQuestions}`;
questions.appendChild(question);
// Create listener for question
const element = document.querySelector(`#question${totalQuestions}`);
element.addEventListener('click', send, false);
totalQuestions++;
}
}
})().catch(err => console.error(err));
</script>
</body>
</html>
There are likely more elegant ways to do this, but I wanted to get an answer out to you ASAP.
Note: I used vanilla javascript over jQuery to cut down on page load times and because I'm more familiar with it.
I have SPA multi view application in AngularJS, I have defined $interval which is started from another view Controller. When i click a btn with function called and line $interval.cancel(); in it, it does not stop.
Here are examples of my code:
MainController:
$scope.$on("startInterval", function () {
$interval(function warningsControl() {
console.log("Timer stamp!");
$.ajax({
// some web api call which works fine
})
}, 10000);
});
$scope.stop = function () {
$interval.cancel();
}
$scope.logoutButton = {
text: "Logout",
type: "normal",
visible: false,
onClick: function () {
// some working code
$scope.stop();
var logoutBtn = $("#logout-btn").dxButton("instance");
logoutBtn.option({
visible: false
});
}
}
And SecondController:
$scope.authenticateButton = {
type: "default",
text: "Log In",
onClick: function () {
$.ajax({
// some web api calling
success: (data) => {
// some working code
$rootScope.$broadcast("startInterval");
}
})
}
}
This code start interval and everithing is running OK, until the point i click Logout btn - it made everithing except stoping the interval.
Any ideas how to fix it? I would be grateful for advice.
The $interval function should return some sort of ID which you can pass into $interval.cancel(). For example:
var int_id = $interval( func, time )
//...later...
$interval.cancel(int_id)
I am new to RecordRTC.js, i have simple application that record audio and video and save that video. this is working fine if i record video using headphone. but if i remove the headphone and try to record video then it creating some terrible noise. some time happen like if i refresh the page then it not making the noise but if i plugged-in the headphone and remove it and press the record button then it start making the noise.
here is my code to start recording.
function captureUserMedia(mediaConstraints, successCallback, errorCallback) {
navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
}
function onMediaSuccess(stream) {
streamMedia = stream;
var videoPreview = document.getElementById('webrtcVideo');
var videoFile = !!navigator.mozGetUserMedia ? 'video.gif' : 'video.webm';
videoPreview.src = window.URL.createObjectURL(stream);
videoPreview.play();
recordVideo = RecordRTC(stream, {
type: 'video'
});
recordVideo.startRecording();
}
function onMediaError(e) {
console.error('media error', e);
}
/**
* This function will be called from html on click of record button.
*/
function startRecording() {
captureUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
}
RecordRTC
var mediaConstraints = {
video: true,
audio: {
mandatory: {
echoCancellation: false,
googAutoGainControl: false,
googNoiseSuppression: false,
googHighpassFilter: false
},
optional: [{
googAudioMirroring: false
}]
},
};
function captureUserMedia(mediaConstraints, successCallback,errorCallback) {
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(successCallback)
.catch(errorCallback);
}