diff --git a/README.md b/README.md index 7aae189..2c4512e 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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). diff --git a/SoroushBot.py b/SoroushBot.py new file mode 100644 index 0000000..ba694ec --- /dev/null +++ b/SoroushBot.py @@ -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 diff --git a/client.py b/client.py index 90f04a2..c8b902a 100644 --- a/client.py +++ b/client.py @@ -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'} @@ -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, @@ -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) @@ -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) @@ -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, @@ -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) @@ -184,21 +200,26 @@ 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, @@ -206,17 +227,22 @@ def send_location(self, to, latitude, longitude, caption='', keyboard=None): '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 @@ -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: diff --git a/examples/send_attachment.py b/examples/send_attachment.py deleted file mode 100644 index 7710ae8..0000000 --- a/examples/send_attachment.py +++ /dev/null @@ -1,31 +0,0 @@ -from sys import path -path.append('..') -from client import Client -from os.path import getsize -import ntpath - -bot_token = 'your bot token' - -bot = Client(bot_token) - -try: - to = 'user chat_id' - file_path = 'your file path' - - [error, file_url] = bot.upload_file(file_path) - - if error: - print('error in uploading file: {}' .format(error)) - else: - print('file uploaded successfully with url: {}' .format(file_url)) - - [error, success] = bot.send_attachment(to, file_url, ntpath.basename(file_path), getsize(file_path), - caption='your caption') - - if success: - print('Message sent successfully') - else: - print('Sending message failed: {}' .format(error)) - -except Exception as e: - print(e.args[0]) diff --git a/examples/send_file.py b/examples/send_file.py new file mode 100644 index 0000000..42f43b7 --- /dev/null +++ b/examples/send_file.py @@ -0,0 +1,18 @@ +from sys import path +path.append('..') +from SoroushBot import SoroushBot + +bot_token = 'your bot token' +bot = SoroushBot(bot_token) + +to = 'user chat_id' +path = 'your file path' + +[error, success] = bot.sendFile( + target_id = to, + file_path = path, + caption='Your Caption' + ) + +if error: + print('error in sending file: {}' .format(error)) diff --git a/examples/send_image.py b/examples/send_image.py index 964f80c..e649ba0 100644 --- a/examples/send_image.py +++ b/examples/send_image.py @@ -1,39 +1,20 @@ from sys import path path.append('..') -from client import Client -from os.path import getsize -import ntpath +from SoroushBot import SoroushBot bot_token = 'your bot token' +bot = SoroushBot(bot_token) -bot = Client(bot_token) +to = 'user chat_id' +path_image = 'image path' +path_image_thumbnail = 'thumbnail path' -try: - to = 'user chat_id' - image_path = 'image path' - image_thumbnail_path = 'thumbnail path' +[error, success] = bot.sendImage( + target_id = to, + image_path = path_image, + image_thumbnail_path = path_image_thumbnail , + caption='Your Caption' + ) - [image_error, image_url] = bot.upload_file(image_path) - if image_error: - print('error in uploading image: {}' .format(image_error)) - else: - print('image uploaded successfully with url: {}' .format(image_url)) - - if image_url: - [thumbnail_error, thumbnail_url] = bot.upload_file(image_thumbnail_path) - if thumbnail_error: - print('error in uploading thumbnail: {}' .format(thumbnail_error)) - else: - print('thumbnail uploaded successfully with url: {}' .format(thumbnail_url)) - - [error, success] = bot.send_image(to, image_url, ntpath.basename(image_path), getsize(image_path), 512, 512, - thumbnail_url, - caption='your caption') - - if success: - print('Message sent successfully') - else: - print('Sending message failed: {}' .format(error)) - -except Exception as e: - print(e.args[0]) +if error: + print('error in sending image: {}' .format(error)) diff --git a/examples/send_location.py b/examples/send_location.py index a9d54ea..c8d728c 100644 --- a/examples/send_location.py +++ b/examples/send_location.py @@ -1,20 +1,19 @@ from sys import path path.append('..') -from client import Client +from SoroushBot import SoroushBot bot_token = 'your bot token' +bot = SoroushBot(bot_token) -bot = Client(bot_token) +to = 'user chat_id' -try: - to = 'user chat_id' +[error, success] = bot.sendLocation( + target_id = to, + latitude = 35.7448416, + longitude = 51.3753212 , + caption='Your Caption' + ) - [error, success] = bot.send_location(to, 35.7448416, 51.3753212) +if error: + print('error in sending Location: {}' .format(error)) - if success: - print('Message sent successfully') - else: - print('Sending message failed: {}' .format(error)) - -except Exception as e: - print(e.args[0]) diff --git a/examples/send_text.py b/examples/send_text.py index 0ce16b3..19914bf 100644 --- a/examples/send_text.py +++ b/examples/send_text.py @@ -1,20 +1,14 @@ from sys import path path.append('..') -from client import Client +from SoroushBot import SoroushBot bot_token = 'your bot token' -bot = Client(bot_token) +bot = SoroushBot(bot_token) -try: - to = 'user chat_id' +to = 'user chat_id' - [error, success] = bot.send_text(to, 'Your text') +[error, success] = bot.sendText(to, 'Your text') - if success: - print('Message sent successfully') - else: - print('Sending message failed: {}' .format(error)) - -except Exception as e: - print(e.args[0]) +if error: + print('Sending message failed: {}' .format(error)) diff --git a/examples/send_video.py b/examples/send_video.py index e7a7769..3042fd4 100644 --- a/examples/send_video.py +++ b/examples/send_video.py @@ -1,41 +1,20 @@ from sys import path path.append('..') -from client import Client -from os.path import getsize -import ntpath +from SoroushBot import SoroushBot bot_token = 'your bot token' +bot = SoroushBot(bot_token) -bot = Client(bot_token) +to = 'user chat_id' +path_video = 'your video path' +path_video_thumbnail = 'your thumbnail of video path' -try: - to = 'user chat_id' - video_path = 'your video path' - video_thumbnail_path = 'video thumbnail path' - video_duration_in_milliseconds = 7000 +[error, success] = bot.sendVideo( + target_id = to, + video_path = path_video, + video_thumbnail_path = path_video_thumbnail , + caption='Your Caption' + ) - [video_error, video_url] = bot.upload_file(video_path) - if video_error: - print('error in uploading video: {}' .format(video_url)) - else: - print('video uploaded successfully with url: {}' .format(video_url)) - - if video_url: - [thumbnail_error, thumbnail_url] = bot.upload_file(video_thumbnail_path) - if thumbnail_error: - print('error in uploading thumbnail: {}' .format(thumbnail_error)) - else: - print('thumbnail uploaded successfully with url: {}' .format(thumbnail_url)) - - [error, success] = bot.send_video(to, video_url, ntpath.basename(video_path), getsize(video_path), - video_duration_in_milliseconds, 512, 512, - thumbnail_url, - caption='your caption') - - if success: - print('Message sent successfully') - else: - print('Sending message failed: {}' .format(error)) - -except Exception as e: - print(e.args[0]) +if error: + print('error in sending video: {}' .format(error)) diff --git a/requirements.txt b/requirements.txt index a944a1c..28f210f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,4 @@ requests sseclient-py +requests_toolbelt +moviepy