Translation On Telegram Bot - php

if (strpos($message, "/translate") === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
file_get_contents($apiURL."/sendmessage?chat_id=".$chatID."&text=Hasil translate: ".$word." : $mymemori ");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(($html = curl_exec($ch)) === false) {
echo 'Curl error: ' . curl_error($ch);
die('111');
}
}
Hello guys i was trying to make translation bot on telegram using php but the output is still error or no output at all. Am using this API https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id
Please help how to get the translation
Error output IMAGES

First, I suggest using cURL, Not file_get_contents.
Second, No need to echo anything, Because the URL will be visited by webhook, Not a human.
Third, You need a method to send requests to Telegram Bot API.
Use this new code:
define('Token', '<your_bot_token>');
# Reading the update from Telegram
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
if (strpos($text, '/translate') === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
//
Bot('sendMessage', [
'chat_id' => $update->message->chat->id,
'text' => "Hasil translate: $word : $mymemori "
]);
}
function Bot(string $method, array $params = [])
{
$ch = curl_init();
$api_url = 'https://api.telegram.org/bot' . Token . "/$method";
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
if ($result->ok == false)
{
throw new Exception($result->description, $result->error_code);
}
return $result->result;
}

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

Eventbrite duplicate event entry

I am trying to code a page to insert an event into eventbrite via PHP Curl
After a bit of trial and error, I have got it working, but instead of inserting one event, 2 are inserted.
Quite new to this, so grateful for any advice/tips...
$token = '######';
$organizerid = '#####';
$timezone = 'Europe/London';
$currency = 'GBP';
$tokenURL = 'https://www.eventbriteapi.com/v3/events/?token='.$token.'&';
$postData = array(
'event.name.html'=>'Curl New Event',
'event.description.html'=>'Test event Eventbrite',
'event.organizer_id'=> $organizerid,
'event.start.utc'=>'2014-11-26T18:00:00Z',
'event.start.timezone'=> $timezone,
'event.end.utc'=>'2014-11-26T19:04:00Z',
'event.end.timezone'=> $timezone,
'event.currency'=> $currency,
'event.venue_id'=>'*****',
'event.online_event'=>'',
'event.listed'=>'',
'event.logo.id'=>'*****',
'event.category_id'=>'',
'event.subcategory_id'=>'',
'event.format_id'=>'',
'event.shareable'=>'on',
'event.invite_only'=>'',
'event.password'=>'',
'event.capacity'=>'25',
'event.show_remaining'=>'on'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenURL);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//need this otherwise you get an ssl error
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
// Check for errors and display the error message
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo $result;
}
curl_close($ch);
You execute your request twice:
$result = curl_exec($ch); // 1st
// Check for errors and display the error message
if(curl_exec($ch) === false) // 2nd
Change the latter to:
if($result === false)
Hope it helps.

PHP - Google translation version 2 is not working with PHP curl, what is causing 403 return error?

I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.

Categories