How to send a random photo in TelegramBot using PHP? - php

I want to send a random photo in TelegramBot, I wrote this code, but it doesn't work. How do I solve this problem?
Code:
$pictures = [
[
"file"=>"data/pictures/pic1.jpg",
],
[
"file"=>"data/pictures/pic2.jpg",
]
];
$random_image = $pictures[rand(0, count($pictures) - 1)];
if ($text == "pictest"){
Bot('SendPhoto',[
'chat_id' => $chat_id,
'photo' => $random_image,
]);
}

Here, we might be missing:
a base domain before images, such as: domain.org/data/pictures/pic1.jpg
or the file index in $random_image
$pictures = [
[
"file" => "data/pictures/pic1.jpg",
],
[
"file" => "data/pictures/pic2.jpg",
],
];
$random_image = $pictures[rand(0, count($pictures) - 1)]["file"];
if ($text == "pictest"){
Bot('SendPhoto',[
'chat_id' => $chat_id,
'photo' => $random_image,
]);
}

Related

Auto-creation of the case part of php Telegram

I have such a code snippet in a Telegram bot in php
case $message == '/nitromonth' || $data_2['callback_query']['data'] == '/nitromonth':
$chat_id = $data['from']['id'];
$method = 'Send a message';
$send_data = [
'text' => $nitromonth,
'reply_markup' => [
'inline_keyboard' => [
[
[
"text" => $translations['ButtonBuy'][$lang],
"callback_data" => '/buy_first_packet_ds'
],
[
"text" => $translations['Repurchase'][$lang],
"callback_data" => '/discord'
],
],
[
[
"text" => $translations['BackCat'][$lang],
"callback_data" => '/products'
],
],
]
]
];
break;
It calls a message with such buttons on command, is there any way to create a .config file for the bot, where it will indicate, for example:
"button[number]" "/commands"
Where [Number] is the ordinal number, 1, 2, 3.. 10, etc.
Where /commands is a command, as indicated in the line
case $message == '/nitromonth' ||$data_2['callback_query']['data'] == '/nitromonth':
there can be nth number of such lines in cfg, each new line generates code above itself when the bot starts, without creating 1000 lines with the same the same code
I'm not a very good php developer, so I'm asking for help

use query_string and range in elasticsearch php client [query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]

i use below code and get below error
for connect php to elasticsearch i use elasticsearch php client
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc'),
'body' => [
'query' => [
'query_string' => [
'query' => "\"$search_text\""
]
]
],
];
if($limit_time['start']){
$params['body']['query']['range']['date_insert']['gte']=$limit_time['start'];
}
if($limit_time['end']){
$params['body']['query']['range']['date_insert']['lte']=$limit_time['end'];
}
error :
{"error":{"root_cause":[{"type":"parsing_exception","reason":"[query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]","line":1,"col":104}],"type":"parsing_exception","reason":"[query_string] malformed query, expected [END_OBJECT] but found [FIELD_NAME]","line":1,"col":104},"status":400}
You should try something like this instead. The query_string and the range queries need to be combined into a bool/filter query:
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc'),
'body' => [
'query' => [
'bool' => [
'filter' => [
[
'query_string' => [
'query' => "\"$search_text\""
]
]
]
]
]
],
];
$range = ['range' => ['date_insert' => []]]
if($limit_time['start']){
$range['range']['date_insert']['gte'] = $limit_time['start'];
}
if($limit_time['end']){
$range['range']['date_insert']['lte'] = $limit_time['end'];
}
$params['body']['query']['bool']['filter'][] = $range;
i solved problem
but thanks a lot "Val" for your help
i use below code :
$params = [
'index'=>'index1,index2',
'from'=>$startfrom,
'size'=>$maxperpage,
'sort' => array('id:desc')
];
if($search_text){
$params['body']['query']['bool']['must'][0]['match_phrase']['src']=$search_text;
}
if($use_time_status){
if($limit_time['start']){
$params['body']['query']['bool']['must'][1]['range']['date_insert']['gte']=$limit_time['start'];
}
if($limit_time['end']){
$params['body']['query']['bool']['must'][1]['range']['date_insert']['lte']=$limit_time['end'];
}
}

Laravel and Guzzle fopen(): can´t find file uploading to an server

I´m trying to upload an image from my server to another one using an API.
I´ve uploaded to my server using native Storage facade and then, call the Guzzle function to upload the file to the other server.
The problem is that I can´t get the local of the file. Let´s see some code:
public function saveImage(Request $request)
{
// return $request;
$consorciado = Consorciado::where('id', '=', $request->consorciado_id)->first();
$documento = Documento::where('doc_id', '=', $request->id)->first();
$documento = new Documento();
$image = request()->file('f');
$documento->consorciado_id = $consorciado->id;
$documento->doc_id = $request->id;
$documento->tipo = $request->tipo;
$documento->remark = $request->remark;
$documento->idTematica = $request->idTematica;
$documento->field1 = $request->field1;
$documento->field2 = $request->field2;
$documento->field3 = $request->field3;
$documento->field4 = $request->field4;
$documento->field5 = $request->field5;
$filename = $consorciado->id . "_" . $documento->doc_id . "." . $image->getClientOriginalExtension();
$documento->nome = $filename;
// dd($doc);
// $file = fopen(Storage::disk('local') . '/' . file_get_contents($image), 'r');
// dd($file);
$client = new Client([
'base_uri' => 'http://gedocflex.com.br:8003/api/file',
]);
$response = $client->request('POST', 'http://gedocflex.com.br:8003/api/file', [
'multipart' => [
[
'name' => 'idTematica',
'contents' => '201'
],
[
'name' => 'f',
// 'contents' => $filename, file_get_contents($image)
'contents' => fopen('/' . $filename, file_get_contents($image), 'w+')
],
[
'name' => 'field1',
'contents' => '132.626.688-85'
],
[
'name' => 'field2',
'contents' => '7758'
],
[
'name' => 'field3',
'contents' => '404'
],
[
'name' => 'field4',
'contents' => '0'
],
[
'name' => 'field5',
'contents' => 'Marcello Dantas Correia'
],
[
'name' => 'remark',
'contents' => 'Enviando do meu servidor para o GED'
],
]
]);
return $response;
Storage::disk('local')->put('public/' . $filename, file_get_contents($image), 'public');
$documento->save(); //salva no meu banco
}
I´m using php artisan storage:link and the error is:
{message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory",…}
exception: "ErrorException"
file: "/Users/marcellopato/Sites/contemplado/app/Http/Controllers/DocumentoController.php"
line: 234
message: "fopen(/1_1.jpeg): failed to open stream: No such file or directory"
trace: [{function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"},…]
As you can see, I get the name of the file, but not its path.
What I am doing wrong?
Anyone?
Thanks in advance!

Trying to upload multiple images using guzzlehttp client in laravel

I am trying to upload multiple images using guzzlehttp client. I have a form in which other type of data('id', 'date','name' e.t.c..) and images are there.
I want to save other data along with image upload through an Api Request.
I am able to save other data, but i am getting problem in uploading images.
In the API i am accessing my image file by
$request->file('images')
but it is showing empty.
My code for calling the API
$images = $request->file('images');
foreach ($images as $image)
{
$body[] = [
'Content-type' => 'multipart/form-data',
'name' => $image->getClientOriginalName(),
'contents' => fopen($image->getRealPath(), 'r')
];
}
$data = $request->all();
$client = new Client();
$response = $client->request('POST', $url, [
'multipart' => $body,
'json' => $data
]);
I'm handling the Api for uploading image below
if ($request->hasFile('images'))
{
$images = $request->file('images');
foreach ($images as $image)
{
$imageRules = [
'file' => 'mimes:png,jpeg,jpg,JPG|max:1024'
];
$imageMessages = [
'file.mimes' => 'One of the images/video is not valid. (only .png, .jpeg, .jpg, .mp4, .x-flv, .x-mpegURL, .MP2T, .3gpp, .quicktime, .x-msvideo, .x-ms-wmv are accepted)',
'file.max' => 'Image size cannot br more than 1 MB'
];
$imageValidator = Validator::make(['file' => $image], $imageRules, $imageMessages);
if ($imageValidator->fails())
{
return response()->json(['success' => false, 'error' => $imageValidator->messages()->first(), 'dashRedirectUrl' => $redirectRoute]);
}
}
$directPath = '/ticket/' . $ticket->id . '/mapping/' . $mappingId . '/images/';
foreach ($images as $image)
{
$option = ['isWatermark' => false];
$imageName = $this->uploadImageToServer($image, $directPath, $option);
$imgInsertData = [
'url' => $imageName,
'title' => $this->getImageTitle($image),
'ticket_mapping_id' => $mappingId,
'type_id' => 1,
];
TicketMappingGallery::create($imgInsertData);
}
}
Note :: My funciton uploadImageToServer() is custom function for uploading the images..
Any help would be appreciated. Drop comment if anything is not clear.
Try this one,
foreach ($image as $img) {
$body[] = [
'name' => 'image[]',
'image_path' => $img->getPathname(),
'image_mime' => $img->getmimeType(),
'image_org' => $img->getClientOriginalName(),
'contents' => fopen($img->getRealPath(), 'r')
];
}
$requestOptions = ['query' => $data, 'multipart' => $body
];

php full text search in elasticsearch

I have a json file which I looped through it and index it in elastic. and after that I want to be able to search through my data.
this is my json file :
https://github.com/mhndev/iran-geography/blob/master/tehran_intersection.json
which looks like :
{
"RECORDS":[
{
"first":{
"name":"ابن بابویه",
"slug":"Ibn Babawayh"
},
"second":{
"name":"میرعابدینی",
"slug":"Myrabdyny"
},
"latitude":"35.601605",
"longitude":"51.444208",
"type":"intersection",
"id":1,
"search":"ابن بابویه میرعابدینی,Ibn Babawayh Myrabdyny,ابن بابویه تقاطع میرعابدینی,Ibn Babawayh taghato Myrabdyny",
"name":"ابن بابویه میرعابدینی",
"slug":"Ibn Babawayh Myrabdyny"
},
...
]
}
when my query is : "mir", I expect my result to be records which has "mirabedini", "mirdamad", "samir", and every other word which contains this string.
but I just get words which are exactly "mir"
and this is my php code for search :
$fields = ['search','slug'];
$params = [
'index' => 'digipeyk',
'type' => 'location',
'body' => [
'query' => [
'match' => [
'fields' => $fields,
'query' => $_GET['query']
]
],
'from' => 0,
'size' => 10
]
];
$client = ClientBuilder::create()->build();
$response = $client->search($params);
and also this my php code for indexing documents.
$client = ClientBuilder::create()->build();
$deleteParams = ['index' => 'digipeyk'];
$response = $client->indices()->delete($deleteParams);
$intersections = json_decode(file_get_contents('data/tehran_intersection.json'), true)['RECORDS'];
$i = 1;
foreach($intersections as $intersection){
echo $i."\n";
$params['index'] = 'digipeyk';
$params['id'] = $intersection['id'];
$params['type'] = 'location';
$params['body'] = $intersection;
$response = $client->index($params);
$i++;
}
I'm using php 7 and elasticsearch 2.3
match query doesn't support wildcard query by default, so you have to use wildcard instead of that.
$fields = ['search','slug'];
$params = [
'index' => 'digipeyk',
'type' => 'location',
'body' => [
'query' => [
'wildcard' => [
'query' => '*'.$_GET['query'].'*'
]
],
'from' => 0,
'size' => 10
]
];
$client = ClientBuilder::create()->build();
$response = $client->search($params);
For more information about wildcard in elastic visit following link : https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html
For that:
'query' => $_GET['query']
You will be burn in hell :D

Categories