how get user id from specific voice channel for move in another channel - move

I make a bot for creating voice channel, not with a command but with to join to specific voice channel.
Actually i'm stuck for move my user into the new voice channel, some one can help me ?
if (idVoiceChannel === "607195759314910090") {
newMember.guild.createChannel('new-general', { type: 'voice' }).then(nM => { nM.setParent(category.id); nM.edit({userLimit: 4}); });
console.log(newUserChannel)
//when channel is created move the user into this
} else if(idVoiceChannel === "607245896250755073") {
}

There is a method for moving a member to channel.
In your case:
newMember.setVoiceChannel(nM)
It looks cleaner if you make your function async,
if (idVoiceChannel === "607195759314910090") {
const nM = await newMember.guild.createChannel('new-general', { type: 'voice' })
nM.setParent(category.id)
nM.edit({userLimit: 4})
newMember.setVoiceChannel(nM)
} else if(idVoiceChannel === "607245896250755073") {
}

Related

Make outbound Teams PSTN call - Azure Communication Services Teams Interoperability

I try to implement a PSTN call feature using Azure Communication Services Teams Interoperability referring this sample code and use case:
https://github.com/Azure-Samples/communication-services-javascript-quickstarts/tree/main/add-1-on-1-cte-video-calling
https://learn.microsoft.com/en-us/azure/communication-services/concepts/interop/custom-teams-endpoint-use-cases#use-case-1-make-outbound-teams-pstn-call
I added the following code to the sample, but I got an error.
startPSTNButton.addEventListener('click',async () => {
try {
console.log('PSTN IN');
const pstnCallee = { phoneNumber: '+81311112222' }
const oneToOneCall = teamsCallAgent.startCall([pstnCallee], { threadId: '00000000-0000-0000-0000-000000000000' });
console.log('Call out');
// Subscribe to the call's properties and events.
subscribeToCall(oneToOneCall);
} catch (error) {
console.error(error);
}
});
Error:
CallingCommunicationError: Starting a one to one with thread ID is invalid.
at TeamsCallAgentImpl.startCall (sdk.bundle.js:183:140138)
at W.value (sdk.bundle.js:161:2267)
at HTMLButtonElement. (client.js:311:1) (anonymous) # client.js:317
Is threadId: '00000000-0000-0000-0000-000000000000' correct?
How to fix the error?
I found it out, and threadId is not required.
https://github.com/Azure/Communication/blob/master/releasenotes/acs-javascript-calling-library-release-notes.md#170-beta1-2022-08-01
const phoneCallee = { phoneNumber: '<PHONE_NUMBER_E164_FORMAT>' }
const oneToOneCall = teamsCallAgent.startCall(phoneCallee );
I try this, and it works fine.

Redux Toolkit Query Graphql + Subscriptions

I really love graphql + rtk query but I cant get the graphql subscriptions working.
I almost directly copied the streaming update example from the redux documentation. But I get the error subscriptions are not supported over HTTP, use websockets instead.
I dont know how to solve this, any help? Can barely find any documentation about graphql subscriptions + rtk query
userStatus: builder.query<
UserStatusSubscriptionSubscription,
{
event_id: string;
user_id: string;
}
>({
query: ({ event_id, user_id }) => ({
document: gql
subscription UserStatusSubscription(
$event_id: uuid!
$user_id: String!
) {
eetschema_event_by_pk(id: $event_id) {
event_attendees(where: { user_id: { _eq: $user_id } }) {
status
event_id
user_id
}
}
}
,
variables: { event_id, user_id },
}),
async onCacheEntryAdded(
arg,
{ updateCachedData, cacheDataLoaded, cacheEntryRemoved }
) {
// create a websocket connection when the cache subscription starts
const ws = new WebSocket("ws://localhost:8080");
try {
// wait for the initial query to resolve before proceeding
await cacheDataLoaded;
// when data is received from the socket connection to the server,
// if it is a message and for the appropriate channel,
// update our query result with the received message
const listener = (event: MessageEvent) => {
const data = JSON.parse(event.data);
console.log("This is the data from the subscription!", data);
if (data.channel !== arg) return;
updateCachedData((draft) => {
draft = data;
});
};
ws.addEventListener("message", listener);
} catch {
// no-op in case cacheEntryRemoved resolves before cacheDataLoaded,
// in which case cacheDataLoaded will throw
}
// cacheEntryRemoved will resolve when the cache subscription is no longer active
await cacheEntryRemoved;
// perform cleanup steps once the cacheEntryRemoved promise resolves
ws.close();
},
}),
What I found out from the Discord chat that there currently is no support for GraphQL Subscriptions. Discord chat link found on the official website
No subscription support at the moment, but you can build something like that using the chat example from the docs
I cite phryneas (he/him) — 06/11/2021
There is also a github issue, which was closed saying this is not possible and you should use a library like urql or apollo. link
I hope this helps, was looking for an answer for ages.

Apollo server subscription not recognizing Async Iterable

I'm having an issue with Apollo GraphQL's subscription. When attempting to start the subscription I'm getting this in return:
"Subscription field must return Async Iterable. Received: { pubsub: { ee: [EventEmitter], subscriptions: {}, subIdCounter: 0 }, pullQueue: [], pushQueue: [], running: true, allSubscribed: null, eventsArray: [\"H-f_mUvS\"], return: [function return] }"
I have other subscriptions setup and are completely functional - so I can confirm the webserver is setup correctly.
I'm just curious if anyone else has ever ran onto this issue before.
Source code in PR diff (it's an open source project):
https://github.com/astronomer/houston-api/pull/165/files
error in playground
I don't think this is an issue specific to the PR you posted. I'd be surprised if any of the subscriptions were working as is.
Your subscribe function should return an AsyncIterable, as the error states. Since it returns a call to createPoller, createPoller should return an AsyncIterable. But here's what that function looks like:
export default function createPoller(
func,
pubsub,
interval = 5000, // Poll every 5 seconds
timeout = 3600000 // Kill after 1 hour
) {
// Gernate a random internal topic.
const topic = shortid.generate();
// Create an async iterator. This is what a subscription resolver expects to be returned.
const iterator = pubsub.asyncIterator(topic);
// Wrap the publish function on the pubsub object, pre-populating the topic.
const publish = bind(curry(pubsub.publish, 2)(topic), pubsub);
// Call the function once to get initial dataset.
func(publish);
// Then set up a timer to call the passed function. This is the poller.
const poll = setInterval(partial(func, publish), interval);
// If we are passed a timeout, kill subscription after that interval has passed.
const kill = setTimeout(iterator.return, timeout);
// Create a typical async iterator, but overwrite the return function
// and cancel the timer. The return function gets called by the apollo server
// when a subscription is cancelled.
return {
...iterator,
return: () => {
log.info(`Disconnecting subscription ${topic}`);
clearInterval(poll);
clearTimeout(kill);
return iterator.return();
}
};
}
So createPoller creates an AsyncIterable, but then creates a shallow copy of it and returns that. graphql-subscriptions uses iterall's isAsyncIterable for the check that's producing the error you're seeing. Because of the way isAsyncIterable works, a shallow copy won't fly. You can see this for yourself:
const { PubSub } = require('graphql-subscriptions')
const { isAsyncIterable } = require('iterall')
const pubSub = new PubSub()
const iterable = pubSub.asyncIterator('test')
const copy = { ...iterable }
console.log(isAsyncIterable(iterable)) // true
console.log(isAsyncIterable(copy)) // false
So, instead of returning a shallow copy, createPoller should just mutate the return method directly:
export default function createPoller(...) {
...
iterator.return = () => { ... }
return iterator
}

Send param with POST to Botframework (and different channel)

I'm working on bot project, the bot are going to work on different channel (web/messenger and probably other)
I'm actually at the proactive message, we want to send dynamic message to user, for example "You don't talk me from XXX time"
So I've made a new route in bot, for sending message with conversation references, it's work good on emulator/messenger for the moment, but we trying to add parameter to this request but we don't found any way to get param in bot.
server.post('/api/notify/:conversationID', async (req, res) => {
console.log(req)
if (req.params.conversationID){
console.log(req.params.conversationID)
}
for (let conversationReference of Object.values(conversationReferences)) {
if (typeof conversationReferences[req.params.conversationID] !== "undefined"){
await adapter.continueConversation(conversationReferences[req.params.conversationID], async turnContext => {
await turnContext.sendActivity(req.params.message);
});
}else {
await adapter.continueConversation(conversationReference, async turnContext => {
await turnContext.sendActivity(req.params.message);
});
}
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><body><h1>Test send.</h1></body></html>');
res.end();
});
I also tried with GET, and sending parameter in URL like /api/notify/CONVID/MESSAGEtoUSER
But if the message length are more than 70 character, the bot return automatically method don't exist, it's like when the length are 'big' so but understand it like route and not like parameter...
Anyone have idea how can we get the param?
Thank!
EDIT :
Finally I found a way to pass param as POST call.
You need to enable bodyParser of restify, add this line :
server.use(restify.plugins.bodyParser())
in index.js
You can now get the body of POST route call !
:-)
You can achieve this by passing any params in an empty activity via the channelData property. Because the activity includes an empty string in the text property, the activity will not display when passed to the bot.
In this example, the proactive message is initiated from the browser.
server.get('/api/notify/:userId', async (req, res) => {
const { userId } = req.params;
for (const conversationReference of Object.values(conversationReferences)) {
await adapter.continueConversation(conversationReference, async turnContext => {
var reply = { type: ActivityTypes.Message };
reply.channelData = { userId };
reply.text = '';
await turnContext.sendActivity(reply);
});
}
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><body><h1>Proactive messages have been sent.</h1></body></html>');
res.end();
});
Proactive message sending the userId via channelData
userId is received by the bot via activity.channelData
Testing Web Chat also shows userId in the activity.channelData
Hope of help!

How to extract entities in text prompt using bot framework sdk for node.js?

I'm developing a bot using the bot framework for node.js v4. Imagine the following scenario:
user: Hello
bot: How can I help you?
user: What is the deadline for completing the transfer?
bot: What is the value of the transfer?
user: $ 5,000
At this time, I am executing the textprompt to request the value of the transfer and I need to validate if the user entity ($ 5,000) has been identified as the money entity.
This is the dialog stack:
this.addDialog(new WaterfallDialog(DUVIDA_NIVEL_APROVACAO_DIALOG, [
this.initializeStateStep.bind(this),
this.moneyStep.bind(this),
this.captureMoney.bind(this),
this.endConversation.bind(this)
]));
this.addDialog(new TextPrompt(MONEY_PROMPT, this.validateMoneyInput));
And the validate method:
async validateMoneyInput(validatorContext) {
const value = validatorContext.recognized.value; //how to get entities?
if (value == 'money') {
return VALIDATION_SUCCEEDED;
} else {
await validatorContext.context.sendActivity(`What is the value of the transfer?`);
return VALIDATION_FAILED;
}
}
However, in the callback to validate the textprompt, I have only the text sent by the user.
How can I get the entities extracted by Luis within the textprompt validation method?
To get any LUIS results into the dialog waterfall, you first need to capture the results on the turnContext, like so:
if (turnContext.activity.type === ActivityTypes.Message) {
// Returns LUIS matched results
const results = await this.luisRecognizer.recognize(turnContext);
// Results are assigned to the turnContext object and is passed into the dialog stack
turnContext.topIntent = results.luisResult.topScoringIntent;
turnContext.topIntent.entities = results.luisResult.entities;
turnContext.topIntent.value = results.luisResult.query;
// Create a dialog context object.
const dc = await this.dialogs.createContext(turnContext);
const utterance = (turnContext.activity.text || '').trim().toLowerCase();
if (utterance === 'cancel') {
if (dc.activeDialog) {
await dc.cancelAllDialogs();
await dc.context.sendActivity(`Ok... canceled.`);
} else {
await dc.context.sendActivity(`Nothing to cancel.`);
}
}
// If the bot has not yet responded, continue processing the current dialog.
await dc.continueDialog();
// Start the sample dialog in response to any other input.
if (!turnContext.responded) {
await dc.beginDialog(DUVIDA_NIVEL_APROVACAO_DIALOG);
}
}
Now that the results have been passed in, you can access the results via the step.context object, like so:
this.dialogs.add(new TextPrompt(MONEY_PROMPT, this.validateMoneyInput.bind(this)));
async moneyStep(step) {
await step.prompt(MONEY_PROMPT, `What is the value of the transfer?`,
{
retryPrompt: 'Try again. What is the value of the transfer?'
}
);
}
async validateMoneyInput(step) {
// LUIS results passed into turnContext are retrieved
const intent = step.context.topIntent['intent'];
const entity = step.context.topIntent.entities;
console.log(entity);
// Validation based on matched intent
if (intent == 'Money') {
return await step.context.sendActivity('Validation succeeded');
} else if (intent != 'Money') {
return await step.context.sendActivity('Validation failed');
}
}
I also assigned the entities value to a variable for accessing since you were asking about it.
Hope of help!

Resources