Twilio Programmable Chat getChannelByUniqueName throws "Forbidden" Error - node.js

After creating a channel in my backend service, I am trying to join the channel in my react frontend in an useEffect hook like this:
const initChat = async () => {
const chatClient = await Client.create(props.token);
const channel = await chatClient.getChannelByUniqueName(props.room);
if (channel) {
if (channel.status !== "joined") {
chatClient.on("channelJoined", () => {
registerChannelListeners(channel);
});
await channel.join();
} else {
registerChannelListeners(channel);
}
setChannel(channel);
setMessages((await channel?.getMessages()).items);
}
};
}
When initially navigating to the page, the error
upstream.js?a850:136 Uncaught (in promise) Error: Forbidden
at Upstream.actualSend (upstream.js?a850:136)
gets thrown sporadically.
On reloading the page, everything works fine.
The problematic line seems to be:
const channel = await chatClient.getChannelByUniqueName(props.room);
As no further code gets executed. token and room are both assigned with valid values.
In the decoded socket messages, this error message is sent from twilio:
{"method":"reply"...,"http_status":{"code":403,"status":"Forbidden"}}
{"status":403,"message":"User not member of channel","code":50400}
although both participants are invited via the backend with this function:
inviteParticipantToChannel(participant: Participant, channelSid: string) {
this.logger.log(
`Inviting paricipant ${participant.getIdentifier()} to channel ${channelSid}`,
);
return this.twilioClient.chat
.services(process.env.TWILIO_CHAT_SERVICE_ID)
.channels(channelSid)
.invites.create({ identity: participant.getIdentifier() });
}
Is there more that I need to do to enable the participant to find/join the channel?

Have you tried setting a short timeout? The channel resource at twilio might need some time.

Related

Microsoft Bot Framework mixing conversation and dialogs between users who send request to bot at same time

I have implemented a bot using Microsoft Bot Framework SDK 4. The Bot is working fine, however I have experienced its not working when two users sends the request to the bot at same time.
I have printed the turnContext values for the users on each turn and its printing correct user and conversation data, however when the beginDialog calls, then sometimes its encountered with Error or sometimes it's mixing dialog response to users (Bot send response to other user).
I have implemented multiple dialogs steps using Waterfall Dialog: Find below code snippet : Where Message 'Hi there :) Welcome User : Name of the user ' is working fine with multiple users, but beginDialog is not working and mixing response to users.
In bot.ts
adapter.onMessage = async turnContext => {
const results = await adapter.continueDialog()
const recognitionResult = await Luis.recognize(turnContext)
const { topScoringIntent } = recognitionResult
if (topScoringIntent === 'welcome') {
await turnContext.sendActivity(`Hi there :) Welcome User ${turnContext.activity.form.name}` )
await adapter.beginDialog(DialogsTimebot.GreetingDialog, {
recognitionResult
})
}
}
In adapter.ts
async beginDialog(dialog: Dialog, options: object | undefined) {
if (!dialogMap.has(dialog)) {
const id = `dialog-${randomId()}`
const dialogClass = new (class extends ComponentDialog {
constructor() {
super(id)
this.addDialog(
new WaterfallDialog(
`waterfall-${id}`,
dialog.steps.map(step => modStep(step, dialogMap))
)
)
}
})()
dialogMap.set(dialog, { id, dialogClass })
_dialogSet.add(dialogClass)
}
const dialogId = dialogMap.get(dialog)!.id
await _dialogContext.beginDialog(dialogId, options)
},
Can anyone please help how to solve this issue? I have got stuck and not able to find the root cause. Thank you.

How would one create a guild and then give myself an invite link

so I am currently in the process of trying to have a bot create a new guild/discord server and then console.log() an invite link for that so that I can join the guild and set it up to then invite friends. However, I am running into some slight problems as I am unsure as to how to go about this. My thought process is the following:
run : function(msg, client, cmds, disc, args){
const guild = client.guild.create("New Guild");
let invite //(and here get a new guild invite code )
console.log(invite);
}
My first problem is that I am not even sure if the guild creation is valid and how to get a guild invite from a guild object.
I have semi-completed what I wished to do. However, this is not the final thing because there is an error messaged:
DiscordAPIError: Unknown Channel
at RequestHandler.execute (C:\Users\jonas\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\jonas\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/801898492082782310/invites',
code: 10003,
httpStatus: 404
I am unsure what the reason for the error in getting the correct channel but I'll reply to this with the full code when I have solved the problem.
run : function(msg, client, cmds, disc, args){
//console.log("1");
client.guilds.create("New Guild")
.then(value => {
let channel = value.channels.cache.first();
let invite = channel.createInvite({
maxAge: 0, // 0 = infinite expiration
maxUses: 0 // 0 = infinite uses
})
.then(result => {
console.log(result);
})
.catch(console.error);
console.log(invite.url);
})
.catch(console.error);
}
The way I fixed it was that previously the object that it fetched was a category channel object meanwhile I needed a text channel/voice channel to create an invite. The solution I used was the following:
run : function(msg, client, cmds, disc, args){
client.guilds.create("New Guild")
.then(value => {
value.channels.create('new-general', { reason: 'Needed a cool new channel' })
.then(channel => {
let invite = channel.createInvite()
.then(invite => console.log(invite))
.catch(console.error);
console.log(invite.url);
})
.catch(console.error);
})
.catch(console.error);
}
To explain the fix, I had to create a channel in the server to invite someone so before I created an invite I created a new channel and used the newly created channel as the channel for the invite.

Slack bot fails to send message to restricted general channel via chat.postMessage

This is my first time trying to create a slack bot and I am following this template code to the word, I have not made any changes, and just remixed on glitch, copy-pasted the auth tokens correctly, things worked just fine.
That is until I made the #general channel restricted for Full Member users.
This is the error I see in the logs at glitch.
PostMessage Error: restricted_action
Is there an additional scope that I need to set, other than bot ?
Here is the workspace user permissions, I am the owner for this workspace.
Here is the code:
const postAnnouncementToChannel = (user, announcement) => {
const { title, details, channel } = announcement;
let announcementData = {
token: process.env.SLACK_ACCESS_TOKEN,
channel: channel,
text: `:loudspeaker: Announcement from: <#${user}>`,
attachments: JSON.stringify([
{
title: title,
text: details,
footer: 'DM me to make announcements.'
}
])
};
send(announcementData, user);
}
const send = async(data) => {
data.as_user = true; // send DM as a bot, not Slackbot
const result = await axios.post(`${apiUrl}/chat.postMessage`, qs.stringify(data))
try {
if(result.data.error) console.log(`PostMessage Error: ${result.data.error}`);
} catch(err) {
console.log(err);
}
}
Testing it via
https://api.slack.com/methods/chat.postMessage/test
using bot-token says
{
"ok": false,
"error": "restricted_action"
}
Testing this using xoxp-token gives this:-
{
"ok": false,
"error": "missing_scope",
"needed": "chat:write:user",
"provided": "identify,bot"
}
No. You are not missing any scopes. Its just that the user you used to auth your app can not post into the general channel. Apparently admins have restricted who can post messages in that channel, e.g. to admins only.
Either use a user that has posting rights for that channel to auth your app or switch to a different channel for your testing.
Bots are not full members so I had to use user token
xoxp-token
to post to chat.postmessage, with
as_user:false
and had to add a missing_scope that is
chat:write:user
And then I was able to make this work correctly.
Credit goes to #girliemac for helping out on this one.
https://github.com/slackapi/template-announcement-approvals/issues/6
Thanks

Authorization error Skype Bot a day later

The bot works on such a case: the user subscribes to the event, and then the event (event generated in TeamCity) should receive a notification.
The bot works fine within one day. But at night in most cases new events are not sent to the user.
error 401 "Authorization has been denied for this request" is written in the logs when the message is sent to the user (await context.sendActivity(message))
When a user subscribes to an event, I save the link to the conversation.
const reference = TurnContext.getConversationReference(context.activity);
reference => saving to base as string (used JSON.stringify)
When I receive an event, I read the link to the conversation from the database and try to send a message.
const reference = JSON.parse(reference from base)
await adapter.continueConversation(reference, async (context) => {
try {
const reply = await context.sendActivity(message);
const reference = TurnContext
.getReplyConversationReference(context.activity, reply);
} catch (e) {
console.log(e);
}
})
3.The link to the dialogue, after sending the message, is again stored in the database
What could go wrong? Why does the code work fine during the day, and after a long time, stop?
If you send any message to the bot from any user, the messages begin to be sent again.

How to send message using Bale bot into group?

How to send message using Bale bot into group?
for send message using BaleBot, we need to have id of User/Group and have an accessHash. But I can`t get accessHash for send mesage to Group.
It's not too hard, if you have id and access_hash of the group(or channel). you should just make the Peer and after that put it in send_message function.
look at this code. It push a "Hello" to a specified channel after getting start by client.
Note: Remember group and channel are similar.
const SDK = require("balebot");
const BaleBot = SDK.BaleBot;
const TextMessage = SDK.TextMessage;
const Group = SDK.Group;
let bot = new BaleBot('token');
bot.hears(["/start"], (message, responder) => {
console.log(responder._peer)
bot.send(new TextMessage("hello"),responder.peer).then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
});
});

Resources