Login plugin Hooks not running - modx

I am trying to send a 2nd email to my sites admin when a user registers.
I made a postHook snippet that sends an email but it didnt work - the Registration process worked as expected, but I got no 2nd email from the hook.
In testing I set the hook from postHook to preHook and tried again - this time the form didnt process at all - no new user was created and no activation email was sent. It didnt even redirect to the submittedResourceId.
So, I deleted everything in my preHook Snippet, except the return true; and tried again - still nothing.
It appears Login wont run any Hooks at all. I have no idea why.
Would anyone be able to suggest any fixes?
My register snippet is:
[[!Register?
&submitVar=`registerbtn`
&activationResourceId=`19`
&activationEmailTpl=`lgnActivateEmailTpl`
&activationEmailSubject=`Thanks for Registering!`
&submittedResourceId=`23`
&usergroups=`2`
&validate=`nospam:blank,
username:required:minLength=^6^,
password:required:minLength=^6^,
password_confirm:password_confirm=^password^,
fullname:required,
email:required:email`
&preHooks=`adminEmailHook`
]]

I've done something similar before. There is my code:
[[!Register? &postHooks=`sendMessageToAdmin`
Snippet sendMessageToAdmin:
<?php
$message = 'Auto message:<br><br>A new user signed up: '.$hook->getValue('fullname') . ', using email address '.$hook->getValue('email').'.';
$modx->getService('mail', 'mail.modPHPMailer');
$modx->mail->set(modMail::MAIL_BODY,$message);
$modx->mail->set(modMail::MAIL_FROM,'info#domain.com');
$modx->mail->set(modMail::MAIL_FROM_NAME,'My website');
$modx->mail->set(modMail::MAIL_SENDER,'Auto message from my website');
$modx->mail->set(modMail::MAIL_SUBJECT,'Someone signed up');
$modx->mail->address('to','info#domain.com');
$modx->mail->setHTML(true);
if (!$modx->mail->send()) {
$modx->log(modX::LOG_LEVEL_ERROR,'sendMessageToAdmin: An error occurred while trying to send the email: '.$err);
}
$modx->mail->reset();
/* tell our snippet we're good and can continue */
return true;

Related

telegram bot login checking authorization not equal hash

I try to use telegram bot connect website, when I open the website, I get the query and hash when I validate throw node.js and not equal
const key = crypto.createHash('sha256').update(my_bot_token).digest()
const validateHash = crypto.createHmac('sha256', key).update('auth_date=1646xxx\nfirst_name=namexxx\nid=1231xxxx\nAusername=alexLxxx').digest('hex')
console.log(hash === validateHash) false
I don't know where I am going wrong I try to use the npm package telegram-checking-authorization, but the same error
You should add all field data you receive from the request callback but remove the hash field.
Ex:
`auth_date=1665991955
first_name=xxxxx
id=xxxxxx
last_name=xxxxx
photo_url=xxxxxxx
username=xxxxx`
I try and succeed.
It happened to me as well, I described it in My question. You might copy the response from this API: https://oauth.telegram.org/auth/get?bot_id=xxx sometimes the response works with the function, sometimes it doesn't, and honestly, I don't understand why. Try to print user to console and check if the two hashes match!
What I have done is as follow:
I changed my bot's domain to https://www.w3schools.com/ and go to w3school online editor https://www.w3schools.com/js/tryit.asp?filename=tryjs_string_indexof for example, print user object to console (replace the javascript in the online editor with code bellow and then replace YOUR-BOT-NAME in the code with the name of your bot):
<script async src="https://telegram.org/js/telegram-widget.js?21" data-telegram-login="YOUR-BOT-NAME" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
<script type="text/javascript">
function onTelegramAuth(user) {
console.log(JSON.stringify(user, null, 2));
}
</script>
press f12, go to console tab and then login with widget. Check the data printed on the console with your function.

Re-prompting users after invalid input

I'm setting up a reset password intent using Dialogflow, where I'm performing some validation via webhooks. Unfortunately, I'm not able to figure out how to reprompt the user in case of failed validation.
I've tried to trigger the intent again using an event, but it doesn't seem to be working. I've also tried setting the same input contexts to trigger the intent again, but neither seem to work.
So I've created 2 parameters within the intent, which are being filled via prompts, following which I am performing the validation. Here's the code:
function getPasscode(agent) {
console.log(agent.parameters);
if(/^\d{6}$/.test(agent.parameters.code1) && agent.parameters.code1 == agent.parameters.code2) {
// Reset passcode call
} else {
return new Promise((resolve, reject) => {
agent.add("Your codes don't match. Please try again.");
var output = JSON.stringify({"followupEvent": {"name": "GetPasscode", "data": {}}})
resolve(output);
});
}
}
The bot outputs the text properly, but isn't triggering the event, as intended.
Am I missing something?
Remember that Intents represent what the user does and not what your action is trying to do. In general, you don't "trigger" an Intent - the user does.
So if you're "reprompting" the user - send that prompt in your reply to them. Then make sure the Intent is setup to capture their reply. This may involve in your setting an Output Context to narrow which Intents are evaluated to consider the reply.
You can't both send back a response and trigger an Intent with an event. Sending an event from your fulfillment is almost never needed and, when done, discards anything you may already have set for a response. All it does is cause the Intent with the event registered to it to be triggered. (Your code has two problems in this respect - you both try to send a response, and you're trying to send the followup event incorrectly.)
In your use-case, you do not need to call the event as per my understanding. Better way to do this is :
Set-up intent where you ask and confirm the password and store it
Validate this in your webhook
Here is the pseudo code:
if validationPassed {
call your api to reset password
send reset password confirmation output to user
}
if validationFailed {
setup output context to ask-password intent again
send output to user to re-enter the password
}
As #Prisoner says, you do not trigger an intent, the user does. We do the processing and send the response once the intent is triggered.
Hope it helps.

socket.emit() fires twice - socket.io

I'm making a one-to-one chatroom.
Here is my basic algorithm:
accept user's input (nickname) by a form
fetch all the existing connections and rooms from server
check if this nickname already exists:
if exists, form submission return false ; if not exists, ......
Now I'm having a socket.emit() twice bug on step 2.
Here is my client side code:
$('#login').submit(function(e){
socket.emit('getRoomInfo');
socket.on('receiveRoomInfo',function(info){
//Here has some code to fetch person_room list from server.
//e.g, person_room[nickname]= roomNO
if(person_room[nickname]){
alert('User already exists!');
}else{
//show chat
//hide the form
//update person_room list
//do something
}
});
return false;
});
Here is my server side code:
socket.on('getRoomInfo',function(){
socket.emit('receiveRoomInfo', {'person_room': person_room, 'roomNO': roomNO});
});
Bug Description:
Suppose I open up one form (index.html), and input 'John Snow', submit the form. Everything works fine, form gets hidden, chat shows up. Waiting for
the other connection...
Then I open up another form (index.html), and input 'John Snow', submit the form. Window alerts 'User already exists!'. Form isn't submitted.
I erase 'John Snow' and input 'Arya Stark', submit the form. Window still alerts
'User already exists!', but this time, form gets hidden, chat shows
up.
What I've test:
Login form is only submitted once
On client side, socket.emit('getRoomInfo') is triggered twice under Bug Description 3, which means socket.on('receiveRoomInfo') is triggered twice as well. So what happens is, 'Arya Stark' gets pushed into the list by the first time, and in the second time, it turns out she already exists in the list, Hence window still alerts 'User already exists!'.
I've researched a lot of similar questions, but none of them is the same case as this one.
Thanks for help.
I can fix the code, but I'm not able to tell the reason behind this bug.
I discovered that under once form submission, socket.on('receiveRoomInfo') is triggered twice.
So I set a variable var userExists=false under form.submit(),
after detected if(person_room[nickname]), set userExists=true.
Under socket.on('receiveRoomInfo'), surround all the code implementation with if(!userExists), so that we can make sure socket.on('receiveRoomInfo') is only executed once under once form submission.
I will be waiting for few days for a better idea before I vote my own answer.

Clear "pending_update_count" in Telegram Bot

I want to clear all pending_update_count in my bot!
The output of below command :
https://api.telegram.org/botxxxxxxxxxxxxxxxx/getWebhookInfo
Obviously I replaced the real API token with xxx
is this :
{
"ok":true,"result":
{
"url":"",
"has_custom_certificate":false,
"pending_update_count":5154
}
}
As you can see, I have 5154 unread updates til now!! ( I'm pretty sure this pending updates are errors! Because no one uses this Bot! It's just a test Bot)
By the way, this pending_update_count number are increasing so fast!
Now that I'm writing this post the number increased 51 and reached to 5205 !
I just want to clear this pending updates.
I'm pretty sure this Bot have been stuck in an infinite loop!
Is there any way to get rid of it?
P.S:
I also cleared the webhook url. But nothing changed!
UPDATE:
The output of getWebhookInfo is this :
{
"ok":true,
"result":{
"url":"https://somewhere.com/telegram/webhook",
"has_custom_certificate":false,
"pending_update_count":23,
"last_error_date":1482910173,
"last_error_message":"Wrong response from the webhook: 500 Internal Server Error",
"max_connections":40
}
}
Why I get Wrong response from the webhook: 500 Internal Server Error ?
I think you have two options:
set webhook that do nothing, just say 200 OK to telegram's servers. Telegram wiil send all updates to this url and the queque will be cleared.
disable webhook and after it get updates by using getUpdates method, after it, turn on webhook again
Update:
Problem with webhook on your side. You can try to emulate telegram's POST query on your URL.
It can be something like this:
{"message_id":1,"from":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username"},"chat":{"id":1,"first_name":"FirstName","last_name":"LastName","username":"username","type":"private"},"date":1460957457,"text":"test message"}
You can send this text as a POST query body with PostMan for example, and after it try to debug your backend.
For anyone looking at this in 2020 and beyond, the Telegram API now supports clearing the pending messages via a drop_pending_updates parameter in both setWebhook and deleteWebhook, as per the API documentation.
Just add return 1; at the end of your hook method.
Update:
Commonly this happens because of queries delay with the database.
I solved is like this
POST tg.api/bottoken/setWebhook to emtpy "url"
POST tg.api/bottoken/getUpdates
POST tg.api/bottoken/getUpdates with "offset" last update_id appeared before
doing this serveral times
POST tg.api/bottoken/getWebhookInfo
had a look if all away.
POST tg.api/bottoken/setWebhook with filled "url"
If you are using webhook, you can follow these steps
On your web browser, enter the following url with your right value of bot
https://api.telegram.org/bot/getWebhookInf
You will get a result like this on your screen
{"ok":true,"result":{"url":"url_value",...}}
On the displayed result, copy the entire url_value without quotes and replace it on this second url
https://api.telegram.org/bot/setWebhook?url=url_value&drop_pending_updates=True
Enter the second url with right bot and url_value in your web browser then press ENTER
Done!
i solve it by Change file access permissions file - set permissions file to 755
and second increase memory limit in php.ini file
A quick&dirty way is to get a temporary webhook here: https://webhook.site/ and
set your webhook to that (it will answer with a HTTP/200 code everytime, reseting your pending messages to zero)
I faced the same issue for my tele bot after user edited existing message. My bot receives update with editedMessage continuously, but update.hasMessage() was empty. As a result number of updates rocketly increased and my bot stack.
I solved this issue by adding handling for use case when message is missing - send 200 code:
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
update = MAPPER.readValue(event.getBody(), Update.class);
if (!update.hasMessage()) {
return new APIGatewayProxyResponseEvent()
.withStatusCode(200) // -> !!!!!! return code 200
.withBody("message is missing")
.withIsBase64Encoded(false);
}
... ... ...

"immediate_failed" - Could not automatially log in the user

I have a problem when I developed my website with Google+ sign-in:
I did step by step that the doc told me but I always failed at step4:
https://developers.google.com/+/web/signin/
the result was always ""immediate_failed" - Could not automatially log in the user", I just don't kown why, can anyone help me, thanks very much! :-(
Note that in the sample code you pointed to, the "immediate_failed" check is commented out. This is intentional, since the first time a user encounters the Sign-in button on the page, it will fail.
The reason it fails is that when the page first loads, before the user even presses the button, a request is sent to Google to determine if the user has already logged in (via Google or another site, for example). If they are - there is no need for them to log in again, so the button never needs to be shown. But if they have not been logged in already, you will get the "immediate_failed" response, and will need to either show (or not clear) the button.
tl;dr - Don't worry aout getting immediate_failed when the page first loads. This is normal.
As a workaround I use gapi.auth.authorize method in the gapi.auth.signIn callback. Here is my code:
gapi.auth.signIn({
'callback': gPlusLoginCallback
});
function gPlusLoginCallback(authResult) {
if (authResult['status']['signed_in']) {
doSmth(authRes['access_token']);
} else if (authResult['error'] == "immediate_failed") {
gapi.auth.authorize({
client_id: gplusClientId,
scope: 'https://www.googleapis.com/auth/plus.login email',
immediate: true
}, function (authRes) {
if (authRes['status']['signed_in']) {
doSmth(authRes['access_token']);
}
});
}
}
function doSmth(accessToken){
//Do smth
}
Change this setting "immediate: true", to be false " immediate: false".
But if you like to make more complex implementation look at the first sample here https://developers.google.com/api-client-library/javascript/start/start-js. You have to calls to Google's "gapi.auth.authorize({...", the first one with "immediate: true", and the second one with "immediate: false".
The question is old but I faced this issue recently.
In my case, it was because I specified the URI parameter prompt to none. I guess Google doesn't like that if the user has never been logged to your platform before.
Whenever I changed that to consent or totally removed it, it worked great.
In my case, the error was because of explicitly specifying the authorization parameter prompt to 'none',similar to a previous answer.
It worked for me by specifying prompt=None or as per the official docs,you may skip this parameter.

Resources