How to use editMessageCaption correctly in php Telegram Bot? - php

I want to edit caption of photo, but Im getting error Bad Request: message to edit not found
Code :
<?php
require_once 'Telegram.php';
$telegram = new Telegram('bot:TOken');
$result = $telegram->getData();
$text = $result['message'] ['text'];
$chat_id = $result['message'] ['chat']['id'];
$messageID = $result['message']['message_id'];
$content = array('chat_id' => $chat_id, 'message_id' => $messageID, 'caption' => "wadawd");
// $content = array('chat_id' => $chat_id, 'text' => $messageID);
$telegram->editMessageCaption($content);
Error Log :
============[Date]============
[ 2022-02-28 12:36:58 UTC ]
==========[Response]==========
ok: False
error_code: 400
description: Bad Request: message to edit not found
=========[Sent Data]==========
[ref]
ref.update_id= 3618619
ref.message.message_id= 42
ref.message.from.id= 52868936
ref.message.from.is_bot= false
ref.message.from.first_name= Ramana
ref.message.from.last_name= Owner
ref.message.from.language_code= en
ref.message.chat.id= 52868936
ref.message.chat.first_name= Ramana
ref.message.chat.last_name= Owner
ref.message.chat.type= private
ref.message.date= 1646051816
ref.message.text= esfsef
[ref]
ref.message_id=
ref.caption= wadawd
============[Trace]===========
#0 /home/onbvbrh08q4z/public_html/captionbot/Telegram.php(3228): TelegramErrorLogger::log()
#1 /home/onbvbrh08q4z/public_html/captionbot/Telegram.php(111): Telegram->sendAPIRequest()
#2 /home/onbvbrh08q4z/public_html/captionbot/Telegram.php(1633): Telegram->endpoint()
#3 /home/onbvbrh08q4z/public_html/captionbot/test.php(15): Telegram->editMessageCaption()
#4 {main}
I'm using this github repo https://github.com/Eleirbag89/TelegramBotPHP

Bots (using api.telegram.org) cannot edit messages of posts made before the bot was added to the channel.
Hence, Telegram Bot Api shows you the error "message to edit not found"

Related

guzzle: TooManyRedirectsException after downgrading

The code worked correctly on version 7+, however, when the version is downgraded to 6, the function falls with an error.
Code:
<?
define(ZIP_TO_LOCATION_APP, "https://tools.usps.com/tools/app/ziplookup/cityByZip");
function get_location_from_zip($zip_code) {
$client = new GuzzleHttp\Client();
$response = $client->request("POST", ZIP_TO_LOCATION_APP, [
'form_params' => [
'zip' => $zip_code
]
]);
if ($response->getStatusCode() == 200) {
$contents = $response->getBody()->getContents();
$contents = json_decode($contents, true);
$contents["error"] = false;
return $contents;
} else {
return array(
"error" => true
);
}
}
Output:
Fatal error: Uncaught GuzzleHttp\Exception\TooManyRedirectsException: Will not follow more than 5 redirects in C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php:159 Stack trace: #0 C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(94): GuzzleHttp\RedirectMiddleware->guardMax(Object(GuzzleHttp\Psr7\Request), Array) #1 C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php(72): GuzzleHttp\RedirectMiddleware->checkRedirect(Object(GuzzleHttp\Psr7\Request), Array, Object(GuzzleHttp\Psr7\Response)) #2 C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\promises\src\FulfilledPromise.php(41): GuzzleHttp\RedirectMiddleware->GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #3 C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\promises\src\TaskQueue.php(48): GuzzleHttp\Promise\FulfilledPromise::GuzzleHttp\Promis in C:\OpenServer\domains\job-board.loc\api\classes\composer\vendor\guzzlehttp\guzzle\src\RedirectMiddleware.php on line 159
I tried playing around with the allow_redirects option, this can hide the exception, but it still doesn't return a response.

Mailgun call to send message to multiple recipients is not returning to caller - example provided

We are attempting to send an email to multiple recipients using the Mailgun PHP API.
We are running MG PHP lib version 2.8.1.
Our code does the following:
note: email address and domain changed for privacy reasons
log_debugger('g1', 'g1');
$params = array(
'from' => $msg_org . " <" . EMAIL_SENDER . ">",
'to' => array('joe#gmail.com'),
'subject' => 'Hey %recipient.first%',
'text' => 'If you wish to unsubscribe, click http://example.com/unsubscribe/%recipient.id%',
'recipient-variables' => '{"joe#gmail.com": {"first":"Joe", "id":1}}'
);
log_debugger('g1', 'g2');
# Make the call to the client.
$mgresult = $mgClient->messages()->send(MAILGUN_DOMAIN, $params);
log_debugger('g1', 'g3');
// if the email was accepted by Mailgun then indicate the member message was delivered
if ($mgresult->http_response_code >= 200 && $mgresult->http_response_code < 300) {
log_debugger('mgr', $mgresult->http_response_code);
// else the email was not accepted by mailgun so indicate the member message failed to be delivered
} else {
log_debugger('g1', 'g4');
}
The call is successfully getting to MG, but we are not getting any return from MG. We have been sending to MG successfully for sometime and now we are attempting to send to multiple email addresses at one time. Below is the data we are passing in as recorded by our debug log.
2020-08-14 12:47:01 g1
2020-08-14 12:47:01 g1
2020-08-14 12:47:01 g1
2020-08-14 12:47:01 g2
Here is the MG documentation - Notice the error: messages()-send should be messages()->send
require 'vendor/autoload.php';
use Mailgun\Mailgun;
// Instantiate the client.
$mgClient = Mailgun::create('PRIVATE_API_KEY', 'https://API_HOSTNAME');
$domain = "YOUR_DOMAIN_NAME";
$params = array(
'from' => 'Excited User <YOU#YOUR_DOMAIN_NAME>',
'to' => array('bob#example.com, alice#example.com'),
'subject' => 'Hey %recipient.first%',
'text' => 'If you wish to unsubscribe, click http://example.com/unsubscribe/%recipient.id%',
'recipient-variables' => '{"bob#example.com": {"first":"Bob", "id":1},
"alice#example.com": {"first":"Alice", "id": 2}}'
);
// Make the call to the client.
$result = $mgClient->messages()-send($domain, $params);
Any help getting this to work would be greatly appreciated. Logged a ticket with MG, but no reply as of yet.
Method documented by MG for sending message is not quite correct. I had to change the call from:
$mgresult = $mailgun_client->messages()->send(MAILGUN_DOMAIN, array(
to:
$mgresult = $mailgun_client->sendMessage(MAILGUN_DOMAIN, array(

CURL-less HTTP request (returning array)

I am new in PHP and I am trying to access file of another website of mine. So on my web #1 I am trying to send a POST request like this:
<?php
$url = 'http://localhost/modul_cms/admin/api.php'; //Web #2
$data = array(
"Action" => "getNewestRecipe",
"Secret" => "61cbe6797d18a2772176b0ce73c580d95f79500d77e45ef810035bc738aef99c3e13568993f735eeb0d3c9e73b22986c57da60a0b2d6413c5dc32b764cc5897a",
"User" => "joomla localhost",
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
if($result === FALSE){
echo "Not working connection :(";
}else{
echo "HOORAY!";
var_dump($result);
}
And on my web #2 I have some kind of receiver I made. Now I need to return after selecting stuff from my database array of data. So I have code like this on my web #2:
<?php
$action = isset( $_POST["action"] ) ? $_POST["action"] : "";
$secret = isset( $_POST["secret"] ) ? $_POST["secret"] : "";
$user = isset( $_POST["user"] ) ? $_POST["user"] : "";
if(!empty($secret)){
if(!empty($user)){
switch($action){
case 'getNewestRecipe':
getNewestRecipe();
break;
case '':
error();
break;
default:
error();
break;
}
}
}
/* *************** FUNCTIONS ************* */
function getNewestRecipe(){
return array("msg" => "Here is your message!");
}
The problem is everything I get on my web #1 from the response is actually the echo I have there for knowing that the HTTP request reached something (so I've got the message "HOORAY!") but the
var_dump($response)
has empty value (not NULL or something it's literally this):
C:\Program Files (x86)\Ampps\www\joomla30\templates\protostar\index.php:214:string '' (length=0)
Thank you for any help!
On web#1 you are sending "Secret","User","Action" in upper-case, but on web#2 you are accessing $_POST['secret'] (lower-case). Because of this your code never gets to the call of getNewestRecipe() nor to your error() call, thus there is no content / a blank page, but also no error.
Also, you need to output the array your function returns in some way.
An array cannot simply be echod, so you need to serialize it. I suggest using json_encode: echo json_encode(getNewestRecipe());

Uncaught exception 'PDOException' with message 'SQLSTATE[22007] on MS Server PHP

Hi im getting the following error, when making a post request i am using a MS Server, MSSQL database and php for a Oauth2 Solution.
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[22007]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.' in C:\xampp\htdocs\api\OAuth2\Storage\Pdo.php:156 Stack trace: #0 C:\xampp\htdocs\api\OAuth2\Storage\Pdo.php(156): PDOStatement->execute(Array) #1 C:\xampp\htdocs\api\OAuth2\ResponseType\AccessToken.php(84): OAuth2\Storage\Pdo->setAccessToken('02742b6cd16424e...', 'testclient', NULL, 1465910857, NULL) #2 C:\xampp\htdocs\api\OAuth2\GrantType\ClientCredentials.php(58): OAuth2\ResponseType\AccessToken->createAccessToken('testclient', NULL, NULL, false) #3 C:\xampp\htdocs\api\OAuth2\Controller\TokenController.php(205): OAuth2\GrantType\ClientCredentials->createAccessToken(Object(OAuth2\ResponseType\AccessToken), 'testclient', NULL, NULL) #4 C:\xampp\htdocs\api\OAuth2\Controller\TokenController.php(49): OAuth2\Controller\TokenController->grantAccessToken(Object(OAuth2\Request), Object(OAuth2\Response in C:\xampp\htdocs\api\OAuth2\Storage\Pdo.php on line 156
After doing some research i understand the 22007 is related to a date problem, i have changed the formatting of the date.
Here is the code block from the Pdo.php the server is complaining about
public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
{
//convert expires to datestring
//$expires = date('Y-m-d H:i:s', $expires);
$expires = date("Ymd H:i:s", $expires);
//echo $expires . "-------------------";
// if it exists, update it.
if ($this->getAccessToken($access_token)) {
$stmt = $this->db->prepare(sprintf('UPDATE %s SET client_id=:client_id, expires=:expires, user_id=:user_id, scope=:scope where access_token=:access_token', $this->config['access_token_table']));
} else {
$stmt = $this->db->prepare(sprintf('INSERT INTO %s (access_token, client_id, expires, user_id, scope) VALUES (:access_token, :client_id, :expires, :user_id, :scope)', $this->config['access_token_table']));
}
return $stmt->execute(compact('access_token', 'client_id', 'user_id', 'expires', 'scope'));
}
The strange thing is in the terminal and postman when i run a curl post, i get the correct response when i run the request on token.php.
There is a problem with the php_curl.dll on our server which has meant i have to use file_get_contents post request to get the data.
public function getAccess() {
$postdata = http_build_query ( array (
'client_id' => 'testclient',
'client_secret' => 'testpass',
'grant_type' => 'client_credentials'
)
);
$opts = array (
'http' => array (
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create ( $opts );
$result = file_get_contents ( 'http://IPADDRESS/api/token.php', false, $context );
// var_dump($result);
echo $result;
return $result;
}
Im guessing the problem is related to using file_get_contents, as the access token is created from terminal and postman.
Any suggestions would be gratefully appreciated.
Thank you.

SoapClient connection to SoapServer

I need to connect to a SOAP Server from php, I read a lot of documentation, examples and tutorials, but I still cannot make authentication to my server. I have done the work below:
$agencyNumber = 7818619810;
$fullTransmission = false;
//$context = array('header' => 'Content-type: application/soap+xml; charset=utf-8');
$params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => 0/*,$context*/);
$client = new SoapClient("http://link/to/server?wsdl");
$test = $client->__getFunctions();
var_dump($test );// returns the functions my supplier provides, as well __getTypes() gives a bunch of variable arrays ect..
$response = $client->__soapCall('GetTransmissionTicket',array($params) );//line 16 which is mentioned on error print
var_dump($response);
Even though I set $context, when I try to run, I get the error below:
Fatal error: Uncaught SoapFault exception: [HTTP] Cannot process the
message because the content type 'text/xml; charset=utf-8' was not the
expected type 'application/soap+xml; charset=utf-8'. in
C:\xampp\htdocs\xml\inc\connection_test.php:16 Stack trace: #0
[internal function]: SoapClient->__doRequest('http://interfac...', '..//my-provider...', 1, 0) #1
C:..path..test.php(16): SoapClient->__soapCall('GetTransmission...',
Array) #2 {main} thrown in C:..path..test.php on line 16
The remote method I'm trying to call is called GetTransmissionTicket which takes two parameters, (int)agencyNumber and fullTransmission(bool)..
I want to emphasize that there are a lot of threads on this topic, some of which are really close to my question(1, 2, 3 and so on ..), but I really couldn't solve the problem. Please give a hand..
Kind Regards..
Try $params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => false);
instead of $params = array( 'agencyNumber' => 7818619810, 'fullTransmission' => 0);
OR
Use $client = new SoapClient("http://link/to/server?wsdl", array('soap_version' => SOAP_1_1));
because
application/soap+xml is the content-type passed when using SOAP 1.2, text/xml is used with SOAP 1.1,
Reference : how to change content-type of request?
A simple example with soap and php can be
$url="your WSDL url";
$method = "Method you are calling";
$error=0;
$client = new SoapClient($url);
try
{
$info = $client->__call($method, array($param));
}
catch (SoapFault $fault)
{
$error = 1;
errorReport($fault->faultcode,$fault->faultstring);
die;
/*echo '<script type="text/javascript">alert("Sorry,App Returne the following ERROR:'.$fault->faultcode."-".$fault->faultstring.' We will now take you back to our homepage."); window.location = "'.$_SERVER['PHP_SELF'].'";</script> '; */
}
if($error==1)
{
$xml=$fault->faultstring;
}else{
$xml = $info;
}
return $xml;
Try implementing it and let me know. if it works for you.
Shouldn't the last line be var_dump($response); instead of var_dump($client);
Anyways, you can also try using this to get the result :
$response = $client->GetTransmissionTicket(array($params) );
var_dump($response);
I resolved this problem by switching from SOAP 1.2 to SOAP 1.1:
$this->client = new SoapClient(
$url,
array(
"trace" => TRUE,
"exception" => 0,
"soap_version" => SOAP_1_1,
"cache_wsdl" => WSDL_CACHE_MEMORY,
"local_cert" => 'mycert.pem',
)
);
I will answer my own question so that it helps someone one day. I used nusoap and changed the encoding to utf-8. The code snippet is below:
require_once "nusoap.php";
$client = new nusoap_client("http://interface.--Serivce-Supplier-Link/Service.svc?wsdl", "wsdl");
$client->soap_defencoding = 'UTF-8';
$result = $client->call("GetTransmissionTicket", array( 'agencyNumber' => 13155, 'fullTransmission' => false));
var_dump($result);
Kind Regards
may be little late but could help others. so here it goes:
$params is already an array so you don't have to use array($params) in
$response = $client->__soapCall('GetTransmissionTicket',array($params) );
instead use simple $params while calling.check it like this
$response = $client->GetTransmissionTicket($params);
also use $client->__getTypes(); to verify params to be passed.
use catch to good effect to trace faultstringand faultactor.
at the end if still not getting solution check it with soapUI(a software).

Categories