Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ارسال راحت تر فیلم ،عکس ، فایل و... با ربات به کاربر یا کانال #33

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@

# Soroush Messenger Bot Python SDK
Soroush Messenger Bot Wrapper for Python

## Dependencies ##
- Python 2.7+
- requests
- sseclient-py
Use SoroushBot.py to send video ,image and file easier !

if you can ,please help us to complete this script (SoroushBot.py) .

## Installation ##
Run the below commands
Expand All @@ -18,31 +16,33 @@ pip install -r requirements.txt
## Usage ##

```python
from client import Client
from SoroushBot import SoroushBot

bot_token = 'your bot token'

bot = Client(bot_token)
bot = SoroushBot(bot_token)

to = 'user chat_id'

try:
to = 'user chat_id'
[error, success] = bot.sendText(to, 'Your text')

[error, success] = bot.send_text(to, 'Your text')
if success:
print('Message sent successfully to user')

if success:
print('Message sent successfully')
else:
print('Sending message failed: {}' .format(error))

except Exception as e:
print(e.args[0])
channelid = 'channel id without @'

[error, success] = bot.sendText(channelid, 'Your text',isSendToChannel=True)

if success:
print('Message sent successfully to channel')

```
"to" value in above example is chat_id of a bot user. You can find it in front of 'from' key in a message that user has sent to your bot.
You can see more examples in the [examples](https://github.com/soroush-app/bot-python-sdk/tree/master/examples) directory.

use [SoroushBot](https://github.com/Mahdiali313/bot-python-sdk/blob/master/SoroushBot.py) function becuase it's easier to use!

## Contribute ##
Contributions to the package are always welcome!
- Report any idea, bugs or issues you find on the [issue tracker](https://github.com/soroush-app/bot-python-sdk/issues).
- You can grab the source code at the package's [Git repository](https://github.com/soroush-app/bot-python-sdk.git).
105 changes: 105 additions & 0 deletions SoroushBot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
from client import Client
import os
from os.path import getsize
import ntpath
from moviepy.editor import VideoFileClip

class SoroushBot:

def __init__(self, bot_token):
global b
b= Client(bot_token)

def sendText(self,target_id,caption,isSendToChannel=False):
resualt=b.send_text(target_id,caption,isSendToChannel)
#resualt=[error,success]
return resualt

def imageVideoResalotion(self,path):
clip=VideoFileClip(path)
width = int(round(clip.w))
height = int(round(clip.h))
return [width,height]

def sendImage(self,target_id,image_path,image_thumbnail_path,caption,isSendToChannel=False):
rImage=b.upload_file(image_path)
#rImage=[image_error, image_url]

if rImage[1]:
rThumb = b.upload_file(image_thumbnail_path)
#rThumb=[thumbnail_error, thumbnail_url]
scale=self.imageVideoResalotion(image_path)

resualt = b.send_image(target_id, rImage[1],
ntpath.basename(image_path),
getsize(image_path), scale[0], scale[1],
rThumb[1],
caption,isSendToChannel)
#if(resualt[1] != 'OK'):
# print("paramets that gotten this function",image_path,image_thumbnail_path,caption)
return resualt

else :
#if(rImage[1] != 'OK'):
# print("paramets entered for this function",image_path,image_thumbnail_path,caption)
return rImage


def sendVideo(self,target_id,video_path,video_thumbnail_path,caption,durationSeconds=None,isSendToChannel=False):
rVideo=b.upload_file(video_path)
#rVideo=[video_error, video_url]

if rVideo[1]:
rThumb= b.upload_file(video_thumbnail_path)
#rThumb=[thumbnail_error, thumbnail_url]

if (durationSeconds==None):
clip=VideoFileClip(video_path)
durationSeconds=int(round(clip.duration))

scale=self.imageVideoResalotion(video_path)#[width,height]

resualt= b.send_video(target_id, rVideo[1],
ntpath.basename(video_path),
getsize(video_path),
durationSeconds*1000, scale[0], scale[1],
rThumb[1],
caption,isSendToChannel)
#if(resualt[1] != 'OK'):
# print("paramets that gotten this func",video_path,video_thumbnail_path,caption,durationSeconds)
return resualt

else:
#if(rVideo[1] != 'OK'):
# print("paramets entered for this func",video_path,video_thumbnail_path,caption,durationSeconds)
return rVideo


def sendFile(self,target_id,file_path,caption,isSendToChannel=False):
rFile = b.upload_file(file_path)
#rFile=[error, file_url]

resualt = b.send_attachment(target_id, rFile[1], ntpath.basename(file_path),
getsize(file_path),
caption,isSendToChannel)
return resualt

def sendLocation(self,target_id, latitude, longitude, caption='', keyboard=None,isSendToChannel=False):
resualt=b.send_location(target_id, latitude, longitude, caption, keyboard,isSendToChannel)

return resualt

def sendAudio (self, target_id, audio_path, caption, audio_duration,isSendToChannel=False):
audioUrl=b.upload_file(audio_path)

audiotype = 'PUSH_TO_TALK'
extra_params = {
'fileDuration': audio_duration*1000
}

resualt = b.send_file(target_id, caption,
ntpath.basename(audio_path), audiotype,
audioUrl[1], getsize(audio_path),
extra_params,isSendToChannel)

return resualt
70 changes: 51 additions & 19 deletions client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import json
import os
from time import sleep

from requests_toolbelt import MultipartEncoder

class Client:
HEADERS = {'Content-Type': 'Application/json', 'Accept': 'Application/json'}
Expand Down Expand Up @@ -92,18 +92,23 @@ def send_message(self, post_data):
except Exception as e:
return [e.args[0], False]

def send_text(self, to, text, keyboard=None):

def send_text(self, to, text,sendTochannel=False, keyboard=None):
'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
post_data = {
'type': 'TEXT',
'to': to,
'body': text,
}
if sendTochannel == True :
post_data['majorType']="CHANNEL"
if keyboard is not None:
post_data['keyboard'] = keyboard
return self.send_message(post_data)

def send_file(self, to, body, file_name, file_type, file_url, file_size, extra_params={}):
def send_file(self, to, body, file_name, file_type, file_url, file_size, extra_params={},sendTochannel=False):
'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
post_data = {
'to': to,
'body': body,
Expand All @@ -113,22 +118,26 @@ def send_file(self, to, body, file_name, file_type, file_url, file_size, extra_p
'fileUrl': file_url,
'fileSize': file_size
}

if sendTochannel == True :
post_data['majorType']="CHANNEL"
for key, value in extra_params.items():
post_data[key] = value

return self.send_message(post_data)

def send_image(self, to, image_file_url, image_file_name, image_file_size, image_width=0,
image_height=0, thumbnail_file_url=None, caption='', keyboard=None):
image_height=0, thumbnail_file_url=None, caption='',sendTochannel=False, keyboard=None):

'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
image_file_type = 'IMAGE'
extra_params = {
'imageWidth': 0,
'imageHeight': 0,
'thumbnailUrl': ''
}

if sendTochannel == True :
extra_params['majorType']="CHANNEL"
if int(image_width) and int(image_height):
extra_params['imageWidth'] = int(image_width)
extra_params['imageHeight'] = int(image_height)
Expand All @@ -141,15 +150,18 @@ def send_image(self, to, image_file_url, image_file_name, image_file_size, image
extra_params)

def send_gif(self, to, image_file_url, image_file_name, image_file_size, image_width=0,
image_height=0, thumbnail_file_url=None, caption='', keyboard=None):
image_height=0, thumbnail_file_url=None, caption='',sendTochannel=False, keyboard=None):

'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
gif_file_type = 'GIF'
extra_params = {
'imageWidth': 0,
'imageHeight': 0,
'thumbnailUrl': ''
}

if sendTochannel == True :
extra_params['majorType']="CHANNEL"
if int(image_width) and int(image_height):
extra_params['imageWidth'] = int(image_width)
extra_params['imageHeight'] = int(image_height)
Expand All @@ -162,8 +174,10 @@ def send_gif(self, to, image_file_url, image_file_name, image_file_size, image_w
extra_params)

def send_video(self, to, video_file_url, video_file_name, video_file_size, video_duration_in_milliseconds,
video_width=0, video_height=0, thumbnail_file_url=None, caption='', keyboard=None):
video_width=0, video_height=0, thumbnail_file_url=None, caption='',sendTochannel=False, keyboard=None):

'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
video_file_type = 'VIDEO'
extra_params = {
'thumbnailWidth': 0,
Expand All @@ -172,6 +186,8 @@ def send_video(self, to, video_file_url, video_file_name, video_file_size, video
'fileDuration': video_duration_in_milliseconds
}

if sendTochannel == True :
extra_params['majorType']="CHANNEL"
if int(video_width) and int(video_height):
extra_params['imageWidth'] = int(video_width)
extra_params['imageHeight'] = int(video_height)
Expand All @@ -184,39 +200,49 @@ def send_video(self, to, video_file_url, video_file_name, video_file_size, video
extra_params)

def send_voice(self, to, voice_file_url, voice_file_name, voice_file_size, voice_duration_in_milliseconds,
caption='', keyboard=None):
caption='',sendTochannel=False, keyboard=None):

'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
voice_file_type = 'PUSH_TO_TALK'
extra_params = {
'fileDuration': voice_duration_in_milliseconds
}

if sendTochannel == True :
extra_params['majorType']="CHANNEL"
if keyboard is not None:
extra_params['keyboard'] = keyboard

return self.send_file(to, caption, voice_file_name, voice_file_type, voice_file_url, voice_file_size,
extra_params)

def send_location(self, to, latitude, longitude, caption='', keyboard=None):

def send_location(self, to, latitude, longitude, caption='',sendTochannel=False, keyboard=None):
'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
post_data = {
'type': 'LOCATION',
'latitude': latitude,
'longitude': longitude,
'to': to,
'body': caption
}


if sendTochannel == True :
post_data['majorType']="CHANNEL"
if keyboard is not None:
post_data['keyboard'] = keyboard

return self.send_message(post_data)

def send_attachment(self, to, file_url, file_name, file_size, caption='', keyboard=None):

def send_attachment(self, to, file_url, file_name, file_size, caption='',sendTochannel=False, keyboard=None):
'''if you set sendTochannel =True ,it will send message to channel
(to=id of channel without @ )'''
file_type = 'ATTACHMENT'
extra_params = {}

if sendTochannel == True :
extra_params['majorType']="CHANNEL"
if keyboard is not None:
extra_params['keyboard'] = keyboard

Expand Down Expand Up @@ -325,11 +351,17 @@ def download_file(self, file_url, save_file_path):

def upload_file(self, file_path):
if not os.path.isfile(file_path):
raise ValueError('Invalid file')
raise ValueError('Invalid file (file with this name not exit or maybe remove or incorrect path you given)')

try:
file = {'file': open(file_path, 'rb')}
response = requests.post(self.get_upload_file_url(), files=file)
session = requests.Session()
with open(file_path, "rb") as f:
m = MultipartEncoder({
'file':(file_path.split('/')[-1],f,"application/octet-stream")
})
headers = {"Content-Type": m.content_type}
response = session.post(self.get_upload_file_url(),headers=headers, data=m)
session.close()

if response.status_code == 200:
if response:
Expand Down
31 changes: 0 additions & 31 deletions examples/send_attachment.py

This file was deleted.

Loading