Trying to send my log file to my Telegram group when they request it.
File 'log.log' is located in the same directory
#t_a = ENV['TELEGRAM_API_KEY']
def send_log(chatid)
file = "log.log"
url = "https://api.telegram.org"
u = "#{url}/bot#{#t_a}"
conn = Faraday.new(
url: u
)
conn.post('sendDocument', {chat_id: chatid, document: file })
end
faraday logs
I, [2022-12-13T16:20:25.153221 #6333] INFO -- : 400 //status
I, [2022-12-13T16:20:25.153473 #6333] INFO -- : //headers
{"server"=>"nginx/1.18.0", "date"=>"Tue, 13 Dec 2022 09:20:25 GMT",
"content-type"=>"application/json", "content-length"=>"99",
"connection"=>"keep-alive",
"strict-transport-security"=>"max-age=31536000; includeSubDomains;
preload", "access-control-allow-origin"=>"*",
"access-control-expose-headers"=>"Content-Length,Content-Type,Date,Server,Connection"}
I, [2022-12-13T16:20:25.153624 #6333] INFO -- : //body
{"ok":false,"error_code":400,"description":"Bad Request: wrong file
identifier/HTTP URL specified"}
This is another suggested way, send an open file object.
def send_log(chatid)
file = File.open("log.log")
url = "https://api.telegram.org"
u = "#{url}/bot#{#t_a}"
conn = Faraday.new(
url: u
)
conn.post('sendDocument', {chat_id: chatid, document: file })
end
I, [2022-12-13T16:25:55.845168 #6625] INFO -- :
{"ok":false,"error_code":400,"description":"Bad Request: wrong remote
file identifier specified: Wrong character in the string"}
Related
I'm trying to set a variable separated from each user, for example:
User a: money: 400
User b: money: 300
But I'm trying to make the User a User b thingy the user id, I've already tried
if message.content.startswith('!info'):
if message.author.id in data:
print('true')
else:
print('false')
with open('data.json', 'r+') as file:
data = json.load(file)
data[str(message.author.id)]['money'] += 300
file.seek(0)
json.dump(data, file, indent=4)
But I got an error: "KeyError: {my user id}"
a KeyError means that your user id isn't even in the dictionary in the first place. Try doing this to fix it:
JSON file:
{
"<user_a_id>": {
"money": 0
},
"<user_b_id>" : {
"money": 0
}
}
Python file:
with open('users.json', 'r+') as file:
data = json.load(file)
data[str(message.author.id)] = {"money": 0}
data[str(message.author.id)]['money'] += 300
file.seek(0)
json.dump(data, file, indent=4)
also, author.id is an int so you would have to convert it into an str for it to properly work.
I'm trying to upload a jpg file onto google drive using the api but i'm not having much luck. Although the code does run without errors, the "image" saved in my google drive is untitled and doesn't actually contain data.
Here's how I'm doing it right now in Python:
post_body = "grant_type=refresh_token&client_id={}&client_secret={}&refresh_token={}".format(client_id, client_secret, refresh_token)
r = requests.post(refresh_url, data=post_body, headers={"Content-Type" : "application/x-www-form-urlencoded"})
r_json = json.loads(r.text)
access_token = r_json["access_token"]
media = MediaFileUpload(filename, mimetype="image/jpeg", resumable=True)
body = {
"name" : filename,
"mimeType" : "image/jpeg"
}
drive_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
drive_r = requests.post(drive_url, data=body, headers={"Authorization": "Bearer " + access_token, "Content-type": "image/jpeg"})
When I print drive_r.text, the response I'm getting back is this:
{
"kind": "drive#file",
"id": "1Vt4gP***************",
"name": "Untitled",
"mimeType": "image/jpeg"
}
From your script, I understood that you want to upload a file to Google Drive without using googleapis for Python. In this case, I would like to propose the following modification.
Modification points:
In your script, the data from the file is not included in the request body.
You use uploadType=media. But it seems that you want to include the file metadata. In this case, please use uploadType=multipart.
Pattern 1:
If the file size you want to upload is less than 5 MB, you can use the following script. uploadType=multipart is used.
Modified script:
import json
import requests
access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###' # Please set the filename with the path.
para = {"name": filename}
files = {
'data': ('metadata', json.dumps(para), 'application/json'),
'file': open(filename, "rb")
}
r = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers={"Authorization": "Bearer " + access_token},
files=files
)
print(r.text)
Pattern 2:
If the file size you want to upload is more than 5 MB, you can use the following script. uploadType=resumable is used.
Modified script:
import json
import os
import requests
access_token = r_json["access_token"] # This is your script for retrieving the access token.
filename = '###' # Please set the filename with the path.
filesize = os.path.getsize(filename)
params = {
"name": filename,
"mimeType": "image/jpeg"
}
r1 = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
headers={"Authorization": "Bearer " + access_token, "Content-Type": "application/json"},
data=json.dumps(params)
)
r2 = requests.put(
r1.headers['Location'],
headers={"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)},
data=open(filename, 'rb')
)
print(r2.text)
Note:
These sample scripts supposes that your access token can be used for uploading the file to Google Drive.
Reference:
Upload file data
I tried one sample program for getting an email message in outlook account using IMAP. In this account, I have 20 folders its getting all email messages except these folders (contact, calendar, task) not getting data its throwing server error. How to fix this error.
Code
import imaplib
import pprint
import email
import base64
import json
import re
import os
import fileinput
imap_host = 'outlook.office365.com'
imap_user = 'XXXXXXXXXXX'
imap_pass = 'XXXXXXXXXXXXX'
count = 0
file_path = 'geek.txt'
# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host,993)
# login to server
l = imap.login(imap_user, imap_pass)
# Get Flags,mailbox_name,delimiter using regex
list_response_pattern = re.compile(r'\((?P<flags>.*?)\) "(?P<delimiter>.*)" (?P<name>.*)')
# Get List of Sync folders
list_data = imap.list()
# Check Local Storage is empty Sync All Folders Details.
print(os.stat(file_path).st_size)
if os.stat(file_path).st_size == 0:
global day
# Iterate folders in Sync folder
for i in list_data[1]:
# Get Folder name
sample = re.findall('"\/"(.*)',i.decode("utf-8"))
# Get Message_ids
try:
print("message")
print(sample[0].lstrip().strip('"'))
data = imap.select(sample[0].lstrip())
search_resp, search_data = imap.search( None, "ALL" )
match = list_response_pattern.match(i.decode("utf-8"))
flags, delimiter, mailbox_name = match.groups()
print("1")
print(mailbox_name)
mailbox_name = mailbox_name.strip('"')
print(mailbox_name)
except Exception as e:
print(e)
continue
# Get Current Status of Folder
current_status = imap.status(
'"{}"'.format(mailbox_name),
'(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)',
)
print(current_status)
# Get message using UID and Message_id
msg_ids = search_data[ 0 ].split()
print("total count: ",len(msg_ids))
for i in msg_ids:
print("$$$$$$$$$$$$$$$$$$$$")
print("Message Ids: ", i)
count = count + 1
fetch_resp, fetch_UID = imap.fetch( i, 'UID' )
print("Fetch UID: ", fetch_UID)
day = bytes(str(fetch_UID[0].split()[2]).split("'")[1].split(')')[0],'utf-8')
print("ID: ",day)
fetch_resp, fetch_mdg = imap.uid('fetch', day, '(RFC822)')
print(fetch_mdg)
print("$$$$$$$$$$$$$$$$$$$$$")
email_msg = fetch_mdg[0][1]
if email_msg and isinstance(email_msg, str):
try:
email_msg = email.message_from_string(email_msg)
except :
email_msg = None
elif email_msg and isinstance(email_msg, bytes):
try:
email_msg = email.message_from_bytes(email_msg)
except:
email_msg = None
print("*********************************")
print("Count: ",count)
print("UID: ",day)
print(mailbox_name)
print(email_msg['To'])
print(email_msg['From'])
print(email_msg['subject'])
print(email_msg)
print("*********************************")
# Store Folder details in File
status_details = current_status[1][0].decode("utf-8")
status_details = status_details.split('(')[1].split(')')[0].split(' ')
print(status_details)
if len(msg_ids) == 0:
json1 = json.dumps({'total_count':int(status_details[1]),'UID':0,'UIDNext':int(status_details[5]),'UIDValidity':int(status_details[7]), 'Folder name':mailbox_name})
else:
json1 = json.dumps({'total_count':int(status_details[1]),'UID':int(day),'UIDNext':int(status_details[5]),'UIDValidity':int(status_details[7]), 'Folder name':mailbox_name})
file = open(file_path,'a')
file.write(json1)
file.write("\n")
print('hi')
Response
$$$$$$$$$$$$$$$$$$$$
Message Ids: b'3'
Fetch UID: [b'3 (UID 11)']
ID: b'11'
[(b'3 (RFC822 {757}', b'MIME-Version: 1.0\r\nContent-Type: text/plain; charset="us-ascii"\r\nFrom: Microsoft Exchange Server\r\nTo: "\r\nSubject: Retrieval using the IMAP4 protocol failed for the following message:\r\n 11\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\nThe server couldn\'t retrieve the following message:\r\n\r\nSubject: "Test email Sync 3"\r\nFrom: "Imap Testing" ("/O=3DEXCHANGELABS/OU=3DEXCHANGE ADMINISTRATIVE GROUP=\r\n (FYDIBOHF23SPDLT)/CN=3DRECIPIENTS/CN=3DEBF2483D9A0145A59A48B829B12A45E4-MA=\r\nILBOX1")\r\nSent date: 5/6/2020 2:02:59 AM\r\n\r\nThe message hasn\'t been deleted. You might be able to view it using either =\r\nOutlook or Outlook Web App. You can also contact the sender to find out wha=\r\nt the message says.=\r\n'), b' UID 11 FLAGS (\\Seen))']
$$$$$$$$$$$$$$$$$$$$$
Server Error
Subject: Retrieval using the IMAP4 protocol failed for the following message:
7
Content-Transfer-Encoding: quoted-printable
The server couldn't retrieve the following message:
Subject: "Testing"
Sent date: 5/6/2020 2:01:54 AM
The message hasn't been deleted. You might be able to view it using either =
Outlook or Outlook Web App. You can also contact the sender to find out wha=
t the message says.=
I have around 20 folders I iterate one by one get current status of folder and stored in sample file. Its successfully working.but I tried to print email messages some folders (contact,calender,task) its showing this response.
I try to send messages to icq via jabber-transport. I tried to use code from this answer
XMPP transport to another protocol, but I got this message:
DEBUG -- : SENDING:
<message to='12345#icq.jabber.blahblah.ru' xmlns='jabber:client'><body>test
message from robot</body></message>
=> nil
DEBUG -- : RECEIVED:
<message from='12345#icq.jabber.blahblah.ru' to='myjit#blahblah.ru/83076
14161416233482839674' type='error'><error code='401' type='auth'><not-authorized
xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/><text xmlns='urn:ietf:params:xml:n
s:xmpp-stanzas'>Error. You must log into the transport before sending messages.<
/text></error><body>test message from robot</body></message>
Please explain me: What am I doing wrong? Thanks in advance.
Here's my code
require 'rubygems'
require 'xmpp4r/client'
include Jabber
Jabber.debug = true
jid = JID::new('myjit#blahblah.ru')
pass = 'pwd'
server = 'jabber.blahblah.ru'
port = '5223'
subj = 'Nagios notification'
user = '12345#icq.jabber.blahblah.ru'
text = 'AAAA AAAA AAAA'
cl = Jabber::Client::new(jid)
cl.use_ssl = true
cl.connect(server,port)
cl.auth(pass)
#connect to transport
reg=Jabber::Iq.new_register "54321", "pwd2"
reg.to="icq.jabber.blahblah.ru"
cl.send reg
mes = Message::new(user,text)
cl.send(mes)
cl.close()
Updated code:
cl.connect(server,port)
cl.auth(pass)
# sending initial presence
p = Jabber::Presence.new
cl.send p
mes = Message::new(user,text)
mes.type = :chat
cl.send(mes)
cl.close()
returns:
D, [2014-11-18T19:01:35.986182 #8084] DEBUG -- : SENDING:
<presence xmlns='jabber:client'/>
=> nil
irb(main):027:0> D, [2014-11-18T19:01:36.048980 #8084] DEBUG -- : RECEIVED:
<presence from='icq.jabber.blahblah.ru' to='myjit#blahblah.ru' type='subscri
be'><status/></presence>
and still doesnt work
You only need to register transport only first time, then you need to send initial presence after session creation.
I am trying to create a simple http server but when i send an png file firefox tells me that there are problems with the image. (the image can not be display).
I changed the content type to octed-stream so i can download the file from the browser.
By comparing the original image and the downloaded image with the text editor I realized that the downloaded one missed some lines in the beginning.
# Provides TCPServer and TCPSocket classes
require 'socket'
server = TCPServer.new('localhost', 1234)
ary = Array.new
f = File.binread '/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
loop do
socket = server.accept
request = socket.gets
index1 = request.index(' ');
index2 = request.index(' ',index1+1);
index3 = request.index("\r\n");
index4 = request.length;
method = request[0,index1]
URI = request[index1+1,index2-index1-1]
version = request[index2+1,index3-index2-1]
CRLF = b2s((request[index3,2] == "\r\n"))
if (URI == "/Shrek" || URI == "/index.html")
socket.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: image/png\r\n" +
"Connection: close\r\n\r\n"
ary = Array.new
f = File.binread '/Users/serrulez/Documents/GIT/KOS_Simple_HTTP_Server/Shrek.png'
#if I print 'f' here to the console i get the hole image, but downloaded from the browser
#the upper part ist cut
puts f
ary.push(f)
socket.write(ary) # <- update, forgot to copy this line
end
socket.close
end
I now get the whole image with the above code but my characters are escaped.
The original image starts with :
�PNG
IHDR�H
�_jsRGB���gAMA���a
[...]
and the image I receive with the browser starts with;
["\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x00\xF3\x00\x00\x01H\b\x02\x00\x00\x00\n\xEE_j\x0
I solved the problem by myself. The last piece to add was the encoding (see below)
if (URI == "/Shrek")
socket.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: image/png; charset=utf-8\r\n" +
"Connection: close\r\n\r\n"