def httpPOST(self, url):
    # Increment request counter
    self.postReqs += 1

    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    now = datetime.datetime.now() # Current timestamp

    fields = []
    fields.append(('video[name]', 'NewHTTPClient uploading ELL_PART_5_768k.wmv'))
    fields.append(('video[author]', 'NewHTTPClient'))

    # Get current timestamp - set as description
    now = datetime.datetime.now()
    fields.append(('video[description] Upload occured at ', str(now)))
    
    # Read file
    f = open('ELL_PART_5_768k.wmv', 'r')    
    data = f.read()
    f.close()
    self.txBytes += len(data)
    
    file = ('video[movie]', 'ELL_PART_5_768k.wmv', data)
    files = []
    files.append(file)

    host = url
    selector = {}

    post_multipart(host, selector, fields, files)
Ejemplo n.º 2
0
        def reply(msg=None,
                  img=None,
                  audio=None,
                  document=None,
                  location=None):
            if msg:
                resp = urllib2.urlopen(
                    BASE_URL + 'sendMessage',
                    urllib.urlencode({
                        'chat_id': str(chat_id),
                        'text': msg.encode('utf-8'),
                        'disable_web_page_preview': 'true',
                        'reply_to_message_id': str(message_id),
                    })).read()

            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])

            elif audio:
                resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('audio', 'audio.mp3', audio),
                ])

            elif document:
                resp = multipart.post_multipart(BASE_URL + 'sendDocument', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('document', 'document.pdf', document),
                ])

            elif location:
                resp = urllib2.urlopen(
                    BASE_URL + 'sendLocation',
                    urllib.urlencode({
                        'chat_id': str(chat_id),
                        'latitude': location[0],
                        'longitude': location[1],
                        'reply_to_message_id': str(message_id),
                    })).read()

            else:
                logging.error('no msg or action specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 3
0
        def reply(msg=None, img=None):
            if msg:
                '''resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'reply_to_message_id': str(message_id),
                })).read()'''
                resp = urllib2.urlopen(
                    BASE_URL + 'sendMessage',
                    urllib.urlencode({
                        'chat_id': str(chat_id),
                        'text': msg.encode('utf-8'),
                        'disable_web_page_preview': 'True',
                    })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 4
0
        def reply(msg=None, img=None, aux=None, esp=None):
            resp = None
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                'chat_id': str(chat_id),
                'text': msg,
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            elif aux:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(aux),
                    'text': 'Olá jogadores do focar_bot, estivemos passando por alguns problemas na última hora como alguns devem ter percebido. Caso não estejam conseguindo jogar, recomendamos que cancelem o jogo atual e começem um novo. Caso ainda assim não estejam conseguindo jogar, contate @cristoferoswald ou @bcesarg6. Desculpem o inconveniente.'
                    #'text':'\t'+emoji_gritar+'***AVISO***'+emoji_gritar+'\nJogadores do forca_bot, uma nova versão do bot foi lançada! A versão 2.0 traz muitas novidades e uma interface totalmente nova. Recomendamos que você passe a utilizar o novo bot. Basta clicar em @PlayHangmanBot. Informamos que essa versão do bot não receberá mais atualizações e eventualmente será desligada, portanto utilizem o novo. Avisem seus amigos e se divirtam!',
                    #'disable_web_page_preview': 'true',
                    #'reply_to_message_id': str(message_id),
                })).read()
            elif esp:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(-34151177),
                    'text': 'Novo chat criado',
                    #'disable_web_page_preview': 'true',
                    #'reply_to_message_id': str(message_id),
                })).read()
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 5
0
def _postSS(screenshot):

	fileName = time.strftime('ss (%Y-%m-%d at %H.%M.%S).' + FORMAT)

	# split the apiKey for the basicAuth
	config.apiKey = config.apiKey.lower()
	l = int(len(config.apiKey)/2)
	basicAuth = (config.apiKey[:l], config.apiKey[l:])

	# save file into buf
	picBuf = StringIO.StringIO()
	screenshot.save_to_callback(_saveToBuf, FORMAT, {}, {'buf' :picBuf})

	# build file list
	fileList = [('media', fileName, picBuf.getvalue())]

	if NO_INTERNET:
		link = "<mediaurl>http://puu.sh/2ES4oa.png</mediaurl>"
	else:
		link = multipart.post_multipart(SERVER, API_END_POINT, files=fileList, basicAuth=basicAuth)

	print link


	# link looks like "<mediaurl>http://puu.sh/2ES4o.png</mediaurl>"
	# strip open and close tags
	_notify(link[10:len(link) - 11])
Ejemplo n.º 6
0
 def send_image(img, chat_id, caption=''):
     resp = multipart.post_multipart(
         BASE_URL + 'sendPhoto',
         [('chat_id', str(chat_id)), ('caption', caption),
          ('reply_markup', '{"hide_keyboard": true}')], [
              ('photo', 'image.png', img),
          ])
Ejemplo n.º 7
0
        def reply(msg=None, img=None):
            if msg:
                resp = urllib2.urlopen(
                    BASE_URL + "sendMessage",
                    urllib.urlencode(
                        {
                            "chat_id": str(chat_id),
                            "text": msg.encode("utf-8"),
                            "disable_web_page_preview": "true",
                            "reply_to_message_id": str(message_id),
                        }
                    ),
                ).read()
            elif img:
                resp = multipart.post_multipart(
                    BASE_URL + "sendPhoto",
                    [("chat_id", str(chat_id)), ("reply_to_message_id", str(message_id))],
                    [("photo", "image.jpg", img)],
                )
            else:
                logging.error("no msg or img specified")
                resp = None

            logging.info("send response:")
            logging.info(resp)
Ejemplo n.º 8
0
        def reply(msg=None, img=None):
            if msg:
                try:
                    encoded_msg = msg.encode('utf-8')
                except UnicodeEncodeError:
                    encoded_msg = unicode(msg, 'utf-8').encode('utf-8')

                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': encoded_msg,
                    'disable_web_page_preview': 'true',
                    'reply_to_message_id': str(message_id),
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified')

                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 9
0
def _postSS(screenshot):

    fileName = time.strftime('ss (%Y-%m-%d at %H.%M.%S).' + FORMAT)

    # split the apiKey for the basicAuth
    config.apiKey = config.apiKey.lower()
    l = int(len(config.apiKey) / 2)
    basicAuth = (config.apiKey[:l], config.apiKey[l:])

    # save file into buf
    picBuf = StringIO.StringIO()
    screenshot.save_to_callback(_saveToBuf, FORMAT, {}, {'buf': picBuf})

    # build file list
    fileList = [('media', fileName, picBuf.getvalue())]

    if NO_INTERNET:
        link = "<mediaurl>http://puu.sh/2ES4oa.png</mediaurl>"
    else:
        link = multipart.post_multipart(SERVER,
                                        API_END_POINT,
                                        files=fileList,
                                        basicAuth=basicAuth)

    print link

    # link looks like "<mediaurl>http://puu.sh/2ES4o.png</mediaurl>"
    # strip open and close tags
    _notify(link[10:len(link) - 11])
Ejemplo n.º 10
0
        def reply(msg=None, img=None, parsemode=None, markup=None):
            if msg:
                if markup:
                    markup = markup
                else:
                    markup = { 'hide_keyboard' : True }
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode' : "Markdown", # str(parsemode),
                    'reply_markup' : json.dumps(markup)
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('No message or image specified.')
                resp = None

            logging.info('Send response:')
            logging.info(resp)
Ejemplo n.º 11
0
        def reply(msg=None, img=None, audio=None, document=None, location=None):
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'reply_to_message_id': str(message_id),
                })).read()

            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])

            elif audio:
                resp = multipart.post_multipart(BASE_URL + 'sendAudio', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('audio', 'audio.mp3', audio),
                ])

            elif document:
                resp = multipart.post_multipart(BASE_URL + 'sendDocument', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('document', 'document.pdf', document),
                ])

            elif location:
                resp = urllib2.urlopen(BASE_URL + 'sendLocation', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'latitude': location[0],
                    'longitude': location[1],
                    'reply_to_message_id': str(message_id),
                })).read()

            else:
                logging.error('no msg or action specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 12
0
        def reply(msg=None, img=None, vid=None, voi=None):
            if msg:#to send message
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'parse_mode': 'Markdown',
                    'disable_web_page_preview': 'true',
                    'reply_markup': json.dumps({'keyboard': array,'one_time_keyboard': True})
                    #'reply_to_message_id': str(message_id),,'one_time_keyboard': True
                    })).read()
            elif img:#to send pictures
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id))
                #('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            elif vid:#to send videos
                resp = multipart.post_multipart(BASE_URL + 'sendVideo', [
                    ('chat_id', str(chat_id))
                #('reply_to_message_id', str(message_id)),
                ], [
                    ('video', 'video.mp4', vid),
                ])
            elif voi:#to send audio as vocal messages
                resp = multipart.post_multipart(BASE_URL + 'sendVoice', [
                    ('chat_id', str(chat_id))
                #('reply_to_message_id', str(message_id)),
                ], [
                    ('voice', 'voice.mp3', voi),
                ])
            elif aud:#to send audio
                 resp = mltipart.post_multipart(BASE_URLS + 'sendAudio', [
                      ('chat_id', str(chat_id))
                 #('reply_to_message_id', str(message_id)),
                 ], [
                      ('audio', 'audio.mp3', aud),
                 ])
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 13
0
 def reply(self, chat_id, message=None, photo=None, document=None, gif=None,
           location=None, preview_disabled=True, caption=None):
     if message:
         response = urllib2.urlopen(self.base_url + 'sendMessage',
                                    urllib.urlencode({
                                     'chat_id': str(chat_id),
                                     'text': message.encode('utf-8'),
                                     'disable_web_page_preview':
                                     str(preview_disabled)
                                     })).read()
         self.log('Bot sent reply "' + message + '" to ' +
                  str(chat_id) + '.')
     elif photo:
         self.send_action(chat_id, 'upload_photo')
         parameters = [('chat_id', str(chat_id))]
         reply_markup = ({
             'hide_keyboard': True
         })
         reply_markup = json.dumps(reply_markup)
         parameters.append(('reply_markup', reply_markup))
         if caption:
             parameters.append(('caption', caption.encode('utf-8')))
         response = post_multipart(self.base_url + 'sendPhoto', parameters,
                                   [('photo', 'photo.jpg', photo)])
         self.log('Bot sent photo to ' + str(chat_id) + ' with caption: ' + caption)
     elif gif or document:
         file_name = 'image.gif' if gif else 'document.file'
         self.send_action(chat_id, 'upload_document')
         response = post_multipart(self.base_url + 'sendDocument',
                                   [('chat_id', str(chat_id))],
                                   [('document', (file_name),
                                    (gif if gif else document))])
         self.log('Bot sent document to ' + str(chat_id) + '.')
     elif location:
         response = urllib2.urlopen(self.base_url + 'sendLocation',
                                    urllib.urlencode({
                                     'chat_id': str(chat_id),
                                     'latitude': location[0],
                                     'longitude': location[1]
                                     })).read()
         self.log('Bot sent location to ' + str(chat_id) + '.')
Ejemplo n.º 14
0
 def wrapper(self):
     client = Client(Application(), BaseResponse)
     response = client.get(url, headers={'Accept': accept})
     eq_(response.status_code, status_code)
     if template:
         assert response.template ==template
     f(self, response, response.context, PyQuery(response.data))
     # Validate after other tests so we know everything else works.
     # Hacky piggybacking on --verbose so tests go faster.
     if '--verbose' in sys.argv:
         validator = post_multipart('validator.w3.org', '/check',
                                    {'fragment': response.data})
         assert PyQuery(validator)('#congrats').size() == 1
Ejemplo n.º 15
0
def TelegramSendMessage(userId, data, dataType):
    if dataType == "text":
        return urllib2.urlopen(
            "https://api.telegram.org/bot" + TelegramToken + "/sendMessage",
            urllib.urlencode({
                "chat_id": str(userId),
                "text": data,
                "disable_web_page_preview": "True"
            })).read()
    elif dataType == "image":
        return multipart.post_multipart(
            "https://api.telegram.org/bot" + TelegramToken + "/sendPhoto",
            [("chat_id", str(userId))], [("photo", "image.jpg", data)])
def _invoke(service, opts, pdb):
	import multipart
	try:
		return multipart.post_multipart(
				"helixweb.nih.gov",
				"/cgi-bin/structbio/basic",
				opts + [
				  ( "pdb_file", "chimera", pdb ),
				  ( "what", None, service ),
				  ( "outputtype", None, "Raw" ),
				]
				)
	except:
		raise chimera.NonChimeraError("Error contacting "
				"StrucTools web server")
Ejemplo n.º 17
0
def sendPhoto(chat_id, img):
    try:
        resp = multipart.post_multipart(key.BASE_URL + 'sendPhoto', [
            ('chat_id', str(chat_id)),
        ], [('photo', 'image.jpg', img)])
        logging.info('send photo:')
        logging.info(resp)
    except urllib2.HTTPError, err:
        if err.code == 403:
            p = Person.query(Person.chat_id == chat_id).get()
            p.enabled = False
            p.put()
            logging.info('Disabled user: '******'Unknown exception: ' + str(err))
Ejemplo n.º 18
0
        def reply(msg=None, img=None, stk=None, audio=None, doc=None, fw=None, chat=None):
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg,
                    'disable_web_page_preview': 'true',
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            elif stk:
                resp = urllib2.urlopen(BASE_URL + 'sendSticker', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'sticker': stk,
                })).read()
            elif audio:
                resp = urllib2.urlopen(BASE_URL + 'sendAudio', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'audio': audio,
                })).read()
            elif doc:
                resp = urllib2.urlopen(BASE_URL + 'sendDocument', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'document': doc,
                })).read()
            elif fw:
                resp = urllib2.urlopen(BASE_URL + 'forwardMessage', urllib.urlencode({
                    'chat_id': fw,
                    'from_chat_id': str(chat_id),
                    'message_id': str(message_id),
                })).read()
            elif chat:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': 'target_chat_id',
                    'text': chat.replace("=SEND=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                })).read()
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 19
0
        def send_message(msg=None, img=None): # exactly the same as reply() but no reply_to_message_id parameter
            if msg:
                resp = urllib2.urlopen(BASE_URL + "sendMessage", urllib.urlencode({
                    "chat_id": str(chat_id),
                    "text": msg.encode("utf-8"),
                    "parse_mode": "Markdown",
                    "disable_web_page_preview": "true",
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + "sendPhoto", [
                    ("chat_id", str(chat_id)),
                ], [
                    ("photo", "image.jpg", img),
                ])
            else:
                logging.error("no msg or img specified")
                resp = None

            logging.info("send response: " + str(resp))
Ejemplo n.º 20
0
        def reply(msg=None, img=None):
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'disable_web_page_preview': 'true',
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('No message or image specified.')
                resp = None

            logging.info('Send response:')
            logging.info(resp)
Ejemplo n.º 21
0
        def reply(msg=None, img=None):
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8','ignore'),
                    'disable_web_page_preview': 'false',
                    'parse_mode' : 'HTML'
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id))
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 22
0
 def reply(msg=None, img=None):
     if msg:
         resp = urllib2.urlopen(
             BASE_URL + 'sendMessage',
             urllib.urlencode({
                 'chat_id': str(chat_id),
                 'text': msg.encode('utf-8'),
                 'disable_web_page_preview': 'true',
                 'reply_to_message_id': str(message_id),
                 'parse_mode': 'Markdown',
             })).read()
     elif img:
         resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
             ('chat_id', str(chat_id)),
             ('reply_to_message_id', str(message_id)),
         ], [
             ('photo', 'image.jpg', img),
         ])
     else:
         resp = None  # resp is just a dummy variable
Ejemplo n.º 23
0
def screenshot(x, y, w, h):
	screenshot = gtk.gdk.Pixbuf.get_from_drawable(gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, w, h), gtk.gdk.get_default_root_window(), gtk.gdk.colormap_get_system(), x, y, 0, 0, w, h)

	# Split the apiKey for the basicAuth
	config.apiKey = config.apiKey.lower()
	l = int(len(config.apiKey) / 2)
	basicAuth = (config.apiKey[:l], config.apiKey[l:])

	# Save file into the buffer
	pictureBuffer = StringIO()
	screenshot.save_to_callback(_saveToBuf, FORMAT, {}, {'buffer': pictureBuffer})

	link = post_multipart('puush.me', '/api/tb', files=[('media', strftime('ss (%Y-%m-%d at %H.%M.%S).' + FORMAT), pictureBuffer.getvalue())], basicAuth=basicAuth)

	# At this step, the link looks like '<mediaurl>http://puu.sh/2ES4o.png</mediaurl>'
	if link and link != 'Unauthorized':
		link = link.partition('<mediaurl>')[2].rpartition('</mediaurl>')[0]

	# Notify the user with the link provided (or an error, see below !)
	_notify(link)
Ejemplo n.º 24
0
        def send_message_html(msg=None, img=None):
            # exactly the same as reply() but no reply_to_message_id parameter
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'parse_mode': 'HTML',
                    'disable_web_page_preview': 'true',
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response: ' + str(resp))
Ejemplo n.º 25
0
def _postSS(screenshot):

	fileName = time.strftime('ss (%Y-%m-%d at %H.%M.%S).' + FORMAT)
	# save file into buf
	picBuf = StringIO.StringIO()
	screenshot.save_to_callback(_saveToBuf, FORMAT, {}, {'buf' :picBuf})

	# build file list
	fileList = [('files[]', fileName, picBuf.getvalue())]

	if NO_INTERNET:
		link = "NO INTERNET"
	else:
		response = multipart.post_multipart(SERVER, API_END_POINT, files=fileList)
		try:
			data = json.loads(response)
			link = data["direct"]
			_notify("La imagen se ha subido correctamente", link)
		except ValueError:
			_notify("Error","Error al subir la imagen")
Ejemplo n.º 26
0
        def reply(msg=None, img=None): #Function used to send messages, it recieves a string message or a binary image
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg.encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'reply_to_message_id': str(message_id),
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    ('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified') #If there is no image it puts in the google log the string
                resp = None

            logging.info('send response:')
            logging.info(resp)
Ejemplo n.º 27
0
 def reply(msg=None, img=None, caption=''):
   """Sends a basic reply to a telegram chat"""
   if msg:
     resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
       'chat_id': str(chat_id),
       'text': msg.encode('utf-8'),
       'disable_web_page_preview': 'true',
       'reply_to_message_id': str(message_id),
       'parse_mode': 'Markdown'
     })).read()
   elif img:
     resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
       ('chat_id', str(chat_id)),
       ('reply_to_message_id', str(message_id)),
       ('caption', caption.encode('utf-8'))
     ], [
       ('photo', 'image.jpg', img),
     ])
   else:
     logging.error('no msg or img specified')
     resp = None
Ejemplo n.º 28
0
        def send_message_html(msg=None, img=None):
            # exactly the same as reply() but no reply_to_message_id parameter
            if msg:
                resp = urllib2.urlopen(
                    BASE_URL + 'sendMessage',
                    urllib.urlencode({
                        'chat_id': str(chat_id),
                        'text': msg.encode('utf-8'),
                        'parse_mode': 'HTML',
                        'disable_web_page_preview': 'true',
                    })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response: ' + str(resp))
Ejemplo n.º 29
0
    def post(self):
        urlfetch.set_default_fetch_deadline(60)
        body = json.loads(self.request.body)
        logging.info('request body:')
        logging.info(body)
        self.response.write(json.dumps(body))

        update_id = body['update_id']
        message = body['message']
        message_id = message.get('message_id')
        date = message.get('date')
        text = message.get('text')
        fr = message.get('from')
        chat = message['chat']
        chat_id = chat['id']
        #try: username = chat['username']
        #except: username = '******'

        if not text:
            logging.info('no text')
            return

        def reply(msg=None, img=None):
            if msg:
                try:
                    resp = urllib.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({'chat_id': chat_id,'text': msg})).read()
                except urllib2.HTTPError, err:
                    logging.error(err)
                    resp='error caused'
                #with open('log.txt', 'a+') as myfile:
                #    myfile.write( chat_id + '..........' + date + '...............' + text + '..................' + chat + '...................' + msg + '\n' )

            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                    #('reply_to_message_id', str(message_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
Ejemplo n.º 30
0
	def test_addTorrent(self):
		#create a torrent
		with tempfile.NamedTemporaryFile(delete=True) as fout:
			fout.write(os.urandom(65535))
			
			fout.flush()
			
			torrentFileName= '%s.torrent' % fout.name 
			
			cmd = ['mktorrent','-a','http://127.0.0.1/announce','-o',torrentFileName, fout.name]
			self.assertEqual(0,subprocess.Popen(cmd).wait())
		
		try:
			with open(torrentFileName,'r') as fin:
				response = multipart.post_multipart('127.0.0.1','/nihitorrent/api/torrents', self.cookie, [('title','Test Torrent')],[('torrent','test.torrent',fin.read())])
				response = json.loads(response)
				torrentUrl = response['metainfo']['href']
		except Exception:
			raise
		finally:
			os.remove(torrentFileName)
		
		response = self.open('%s/%s' % ( self.conf['url'] , torrentUrl,))
Ejemplo n.º 31
0
        def reply(msg=None, img=None, stk=None, audio=None, doc=None, fw=None, chat=None, chat1=None, chat2=None, chat3=None, chat4=None, chat5=None):
            if msg:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'text': msg,
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif img:
                resp = multipart.post_multipart(BASE_URL + 'sendPhoto', [
                    ('chat_id', str(chat_id)),
                ], [
                    ('photo', 'image.jpg', img),
                ])
            elif stk:
                resp = urllib2.urlopen(BASE_URL + 'sendSticker', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'sticker': stk,
                })).read()
            elif audio:
                resp = urllib2.urlopen(BASE_URL + 'sendAudio', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'audio': audio,
                })).read()
            elif doc:
                resp = urllib2.urlopen(BASE_URL + 'sendDocument', urllib.urlencode({
                    'chat_id': str(chat_id),
                    'document': doc,
                })).read()
            elif fw:
                resp = urllib2.urlopen(BASE_URL + 'forwardMessage', urllib.urlencode({
                    'chat_id': fw,
                    'from_chat_id': str(chat_id),
                    'message_id': str(message_id),
                    'parse_mode': 'HTML',
                })).read()
            elif chat:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-12787170',
                    'text': chat.replace("=PBZZ=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif chat1:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-36729866',
                    'text': chat1.replace("=STUDENTIPER=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif chat2:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-12604594',
                    'text': chat2.replace("=LAPA=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif chat3:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-7284886',
                    'text': chat3.replace("=3LZ=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif chat4:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-23982686',
                    'text': chat4.replace("=1AK=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            elif chat5:
                resp = urllib2.urlopen(BASE_URL + 'sendMessage', urllib.urlencode({
                    'chat_id': '-18336711',
                    'text': chat5.replace("=1LZ=", "").encode('utf-8'),
                    'disable_web_page_preview': 'true',
                    'parse_mode': 'HTML',
                })).read()
            else:
                logging.error('no msg or img specified')
                resp = None

            logging.info('send response:')
            logging.info(resp)