Error: An API error occurred: invalid_auth - javascript

Hi I'm writing my slack bot, and I want after select, change prev message to a new variat, this is my action which is triggerd after select:
slackInteractions.action({ type: "static_select" }, (payload, res) => {
console.log(payload);
web.chat
.update({
token: slackSigningSecret,
channel: payload.container.channel_id,
ts: payload.container.message_ts,
as_user: true,
text: "Hello World"
})
.catch(err => {
console.log(err);
});
});
And I got error:
Error: An API error occurred: invalid_auth
at Object.platformErrorFromResult (/home/codex/Documents/dan-bot/node_modules/#slack/web-api/dist/errors.js:50:33)
at WebClient.apiCall (/home/codex/Documents/dan-bot/node_modules/#slack/web-api/dist/WebClient.js:485:28)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
code: 'slack_webapi_platform_error',
data: { ok: false, error: 'invalid_auth', response_metadata: {} }
}
This is payload:
{
type: 'block_actions',
team: { id: '//', domain: '*** },
user: {
id: 'U010Q9X59QT',
username: '**',
name: '***',
team_id: '//'
},
api_app_id: '///',
token: '***',
container: {
type: 'message',
message_ts: '1585662258.008100',
channel_id: '****',
is_ephemeral: true
},
trigger_id: '1038328652789.1035324920279.b84d3403b8e44ab0cd53c997ba8b4c72',
channel: { id: '***', name: 'directmessage' },
response_url: 'https://hooks.slack.com/actions/T01119JT287/1040413692903/6TWTQqXhcp453TPREb7uRcPn',
actions: [
{
type: 'static_select',
action_id: 'wkR',
block_id: 'LM9',
selected_option: [Object],
placeholder: [Object],
action_ts: '1585662260.040519'
}
]
}
As token I use my main slack token, using this I'm trying to change block where I seelcted variant to another block, at the moment trying to change as string "Hello world"
Thanks in forward!!!!

Looking back at their documentation for chat.update, the token should be the access token you see on the Oauth & Permissions tab and it starts with xoxb or xoxp. Please check more about their Oauth documentation here: https://api.slack.com/authentication/oauth-v2

I faced the same issue, and eventually found out it was caused by passing the wrong token (copy-paste issues).
What helped me debug it:
Check the structure of the token. Most modern tokens start with xoxb- and have a length of 56 characters
Test that the token works before wrapping it in code, using e.g. Slack's auth test API

Related

cypress.origin throws error: (uncaught exception)Error: on only accepts instances of Function

I am using Cypress with Cucumber.
I am trying to test cross origin login but the origin method keeps on throwing error:
Code:
Given(/^the user login to the Test Page$/, function () {
cy.visit("https://example-originalURL");
cy.get("button").contains("Login").click();
const credentials = {
username: "hello",
password: "user",
};
cy.origin("https://example-newURL", { args: credentials }, ({ username, password }) => {
cy.get("#email", { timeout: 20000 }).type(username);
cy.get("#password").type(password, { log: false });
cy.get("button").contains("Login").click();
});
});
Cypress.config.js
module.exports = defineConfig({
projectId: "t7unhv",
e2e: {
setupNodeEvents(on, config) {
on("file:preprocessor", cucumber());
on('task', {
log(message) {
console.log(message +'\n\n');
return null;
},
});
},
specPattern: "./cypress/e2e/features/*.feature",
chromeWebSecurity: false,
experimentalSessionAndOrigin: true,
defaultCommandTimeout: 15000,
env: {
devCentralUrl: "https://***.dev.***.com.au/login",
testCentralUrl:
"https://***.test.***.com.au/login",
test***: "http://***.test.***.com.au",
dev***: "http://***.dev.***.com.au",
uat***: "https://***.uat.***.com.au",
dataSource: "",
environs: "test",
},
retries: {
runMode: 0,
},
pageLoadTimeout: 15000,
reporter: "mochawesome",
reporterOptions: {
reporterEnabled: "mochawesome",
mochawesomeReporterOptions: {
reportDir: "cypress/reports/mocha",
quite: true,
charts: true,
overwrite: false,
html: false,
json: true,
},
},
},
});
Error:
The following error originated from your test code, not from Cypress.
> on only accepts instances of Function
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
I have tried multiple syntax changes like not passing the credentials as optional argument to cy.origin.
If someone can provide a quick help, that will be great.
If the problem is in the test code, it is likely to be that newURL is undefined. The error message suggests the problem is in the app, but that might be a red herring.
Try just adding a fixed string for the cy.origin() key,
cy.origin('login', { args: credentials }, ({ username, password }) => {
...
})

Error Code 50006 when any gif or sticker is put into chat

My discord script is currently working as intended except in rare situations. When anyone posts a gif or a sticker into the chats I'm monitoring, it crashes and throws back an error 50006 back at me. I tried this myself by sending a regular message and a gif right after. The regular message went through just fine, but the gif threw back an error at me. See the following.
DiscordAPIError[50006]: Cannot send an empty message
at SequentialHandler.runRequest (FILE_LOCATION\node_modules\#discordjs\rest\dist\index.js:748:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (FILE_LOCATION\node_modules\#discordjs\rest\dist\index.js:560:14)
at async REST.request (FILE_LOCATION\node_modules\#discordjs\rest\dist\index.js:1000:22)
at async WebhookClient.send (FILE_LOCATION\node_modules\discord.js\src\structures\Webhook.js:213:15) {
rawError: { message: 'Cannot send an empty message', code: 50006 },
code: 50006,
status: 400,
method: 'POST',
url: 'MYWEBHOOK',
requestBody: {
files: [],
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [],
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
}
}
I make sure the data doesn't equal null before sending it off to a switch statement that checks the channel_id the message is coming from. In there, I verify that there is an author before even sending the webhook. So should I be verifying something other than the author in my second check before sending it off to the webhook?
Example of my switch statement:
function listener(d) {
if (d.author != null) {
if (d.channel_id === CHANNEL_ADDRESS) {
let content = d.content ? d.content : { embeds: d.embeds };
let client = new WebhookClient({ URL: "WEBHOOK_URL" })
client.send(content);
}
}
};

How to use editMessageText with the Telegraf framework?

I have to edit a message when an inline button is pressed.
Here is my code:
bot.action("option2", (ctx) => {
ctx.answerCbQuery();
bot.telegram.editMessageText(
ctx.update.callback_query.message.chat.id,
ctx.update.callback_query.message.message_id,
`Hello`
);
});
I'm getting the error:
{
response: {
ok: false,
error_code: 400,
description: 'Bad Request: message text is empty'
},
on: {
method: 'editMessageText',
payload: {
text: undefined,
chat_id: 'Hello',
message_id: { chat_id: -684957676, message_id: 578 },
inline_message_id: undefined
}
}
}
I'm using the Telegraf framework
I believe that I don't understand the order in which I should pass arguments.
How do I use the editMessageText?
You don't have to make it complex this way.
Just do this:
ctx.editMessageText('Hello')

How to pass redirect_uri in next-auth?

I do authorization via next-auth
import NextAuth from 'next-auth';
export default NextAuth({
providers: [
{
id: 'reddit',
name: 'Reddit',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
scope: 'read submit identity',
type: 'oauth',
version: '2.0',
params: { grant_type: 'authorization_code' },
accessTokenUrl: ' https://www.reddit.com/api/v1/access_token',
authorizationUrl: 'https://www.reddit.com/api/v1/authorize?response_type=code&duration=permanent',
profileUrl: 'https://oauth.reddit.com/api/v1/me',
profile: profile => {
return {
id: profile.id as string,
name: profile.name,
email: null,
};
},
},
],
});
And I am getting error from reddit
/you sent an invalid request
invalid redirect_uri parameter./
How am I supposed to pass this uri in next-auth?
NEXTAUTH_URL variable is also specified
This is how next-auth inserts it into Request URL
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapi%2Fauth%2Fcallback%2Freddit
but I just need
http://localhost:8080
I solved it) u just need to set redirect_uri in your reddit app as
http://localhost:8080/api/auth/callback/reddit

How to set `You and moderator can reply` in bot when posting proactive message to channels?

I am currently developing a bot that posts proactive message to channels. My client wants me to set No reply or You and moderator can reply on the message that posted from the bot proactively. 
What I tried so far:
// post message to channels
const credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
const client = new ConnectorClient(credentials, { baseUri: serviceUrl });
const message = MessageFactory.text(inMessage);
let approveResult = false;
let MessageActivityId = "";
const conversationParams = {
isGroup: true,
bot: {
id: process.env.MicrosoftAppId,
name: process.env.BotName
},
conversationType: 'channel',
channelData: {
channel: {
id: teamsChannelId
}
},
activity: message
};
const msRes = await client.conversations.createConversation(conversationParams).catch(e => console.log(e));
I tried to post the message first, and immediately update the activity and set the type as ActivityTypes.EndOfConversation. However, it doesn't work at all.
const tmpResult = await client.conversations.updateActivity(teamsChannelId, msRes.activityId, {type: ActivityTypes.EndOfConversation})
Error form above updateActivity code: 
RestError: Unknown activity type
at ...(skipped for paths)
{
code: 'BadArgument',
statusCode: 400,
request: WebResource {
streamResponseBody: false,
url: 'https://{service_url}/{channel_id}/activities/{messageActivityId}',
method: 'PUT',
headers: HttpHeaders {
_headersMap: [Object]
},
body: '{"type":"endOfConversation"}',
query: undefined,
formData: undefined,
withCredentials: false,
abortSignal: undefined,
timeout: 0,
onUploadProgress: undefined,
onDownloadProgress: undefined,
proxySettings: undefined,
keepAlive: undefined,
agentSettings: undefined,
operationSpec: {
httpMethod: 'PUT',
path: 'v3/conversations/{conversationId}/activities/{activityId}',
urlParameters: [Array],
requestBody: [Object],
responses: [Object],
serializer: [Serializer]
}
},
response: {
body: '{"error":{"code":"BadArgument","message":"Unknown activity type"}}',
headers: HttpHeaders {
_headersMap: [Object]
},
status: 400
},
body: {
error: {
code: 'BadArgument',
message: 'Unknown activity type'
}
}
}
Is there any method that allows me to do so? Thanks.
It would be better if I could only disable the reply function in Channels from bot programmatically.
Update on 2021-06-28:
Simulation of expected behavior on UI:
Simulation of actual behavior on UI:
I've not actually tested this property myself, but it seems like it should handle what you need: In the Teams app manifest, there is a "NotificationOnly" setting on the bot, which means it should not allow users to converse with it (i.e. "reply"). See more at https://learn.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bots-notification-only

Categories

Resources