How to use editMessageText with the Telegraf framework? - javascript

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')

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 }) => {
...
})

javascript unexepected end of input error I cannot find why

I made a function with a fetch and it shows no errors until I run it. When I run it I get the error below. I ran it through jshint and jslint and they do not show any issues. This is pretty much a copy/paste of a function I have that works fine. Do you all see anything wrong?
Error from browser
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at HTMLInputElement.<anonymous> (admin:429:59)
this.element.querySelector("#product-btn").addEventListener("click", async function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
form=document.getElementById('product-upload');
const fields = {
csrf_token: {
input: document.getElementById('csrf_token'),
error: document.getElementById('csrf_token-error')
},
title: {
input: document.getElementById('title'),
error: document.getElementById('title-error')
},
description: {
input: document.getElementById('description'),
error: document.getElementById('description-error')
},
cost: {
input: document.getElementById('cost'),
error: document.getElementById('cost-error')
},
old_cost: {
input: document.getElementById('old_cost'),
error: document.getElementById('old_cost-error')
}
};
//This shows error in lint but it's jinja for python and works fine
const response = await fetch('{{ url_for('main.upload_products') }}', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
csrf_token: fields.csrf_token.input.value,
title: fields.title.input.value,
description: fields.description.input.value,
cost: fields.cost.input.value,
old_cost: fields.old_cost.input.value
})
});
//THE code below is where the error points to
data = await response.json();
if (response.ok) {
myDropzone.processQueue();
} else {
const errors = data;
form.classList.add('was-validated');
Object.keys(errors).forEach((key) => {
fields[key].input.classList.add('is-invalid');
fields[key].error.innerHTML = errors[key][0];
});
}
});

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

Is there a way to make check on HEX color - Cypress

I am currently busy with testing on Cypress . I am actually new so i am not so familiar with everything around , but i am trying to test a CSS property of background-color on certain element , but the problem is that behind the scenes everything is RGB , but i need to test on HEX . So i ask myself is there a way to do that or a translation should be necessary ?
cy.get('#button-login')
.should('have.css', 'background-color', "#6a7ba3")
ERROR : ...to have CSS property 'background-color' with the value '#6a7ba3', but the value was 'rgb(106, 123, 163)'
You can achieve what you want using the chai-colors assertion plugin.
Install as follows:
npm install chai-colors
Then add this to your code:
import chaiColors from 'chai-colors'
chai.use(chaiColors)
Or this, as applicable:
var chaiColors = require('chai-colors');
chai.use(chaiColors);
Now you can write your assertion like this:
cy.get('#button-login')
.should('have.css', 'background-color')
.and('be.colored', '#6a7ba3')
I was facing error with chai-colors so I used the tinycolor2 library to assert the color as follows
import Toast from './index';
import { themedMount } from '../../../cypress/index';
import tinycolor from 'tinycolor2';
const toastColorMap: Record<string, string> = {
success: '#cff5c4',
error: '#fbcfc8',
};
const toasts = [
{ _id: '1', message: 'success toast notification', type: 'success' },
{ _id: '2', message: '2 success toast notification', type: 'error' },
{ _id: '3', message: 'error toast notification', type: 'error' },
];
describe('Toast.cy.tsx', () => {
it('Toast component renders toasts properly', () => {
themedMount(<Toast toasts={toasts} />);
toasts.forEach((t) => {
const toastElement = cy.contains(t.message);
toastElement.should('have.css', 'background-color').then((bg) => {
const color = tinycolor(bg);
expect(color.toHexString()).equal(toastColorMap[t.type]);
});
});
});
});

Error: An API error occurred: invalid_auth

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

Categories

Resources