0

I am trying to make a script in python that downloads an image from a discord server but it doesnt work

My code

import http.client, json, calendar, os, time, base64
from datetime import datetime


app_token = "token"
channel_id = "id"
web_hk = "api/webhooks/my webhook"
latest_timestamp = ""

def query_server():
    global app_token, channel_id, latest_timestamp

    response = 'Processing...'


    conn = http.client.HTTPSConnection("discordapp.com")
    headers = {"authorization": "Bot " + app_token }
    conn.request("GET", "/api/channels/" + channel_id +"/messages", "", headers)
    r1 = conn.getresponse()

    status = r1.reason
    print(status)

    r = r1.read()
    print(r)
    conversation = json.loads(r.decode('utf-8'))

#    print(json.dumps(conversation, indent=4, sort_keys=True))

    i = 0
    while i < len(conversation) :
        comment = conversation[i]
        i += 1

        timestamp = comment["timestamp"]

        if(timestamp <= latest_timestamp) :
            break

        print(comment)

        if(comment['content'] == 'Go!') :

            print('parsing command')

            style_comment = conversation[i]
            if style_comment['attachments'] == [] :
                response = 'Missing style image'
                break

            content_comment = conversation[i + 1]
            if content_comment['attachments'] == []:
                response = 'Missing content image'
                break


            conn = http.client.HTTPSConnection("cdn.discordapp.com")
            current_time_int = str(int(time.mktime(datetime.utcnow().timetuple())))


            # download style image
            url = style_comment['attachments'][0]['url']
            img_path = url.split("https://cdn.discordapp.com")[1]

            t = url.split("/")
            style_img_filename = current_time_int + "-" + t[-1]

            conn.request("GET", img_path, "", headers)
            r1 = conn.getresponse().read()

            style_file = open(style_img_filename, "wb")
            style_file.write(base64.encodebytes(r1))
            style_file.close()
            os.chmod(style_img_filename, 0o777)

            # download content image
            url = content_comment['attachments'][0]['url']
            img_path = url.split("https://cdn.discordapp.com")[1]

            t = url.split("/")
            content_img_filename = current_time_int + "-" + t[-1]

            conn.request("GET", img_path, "", headers)
            r1 = conn.getresponse().read()

            content_file = open(content_img_filename, "wb")
            content_file.write(base64.encodebytes(r1))
            content_file.close()
            os.chmod(content_img_filename, 0o777)

            output_img_filename = current_time_int + "-output.jpg"


            cmd = "python neural_style.py --content {} --styles {} --output {} --width 500".format(content_img_filename, style_img_filename, output_img_filename)

            print(cmd)
            os.system(cmd)

            break

    print(response)

query_server()

What I get

Traceback (most recent call last):
  File "neural_style.py", line 216, in <module>
    main()
  File "neural_style.py", line 119, in main
    content_image = imread(options.content)
  File "neural_style.py", line 201, in imread
    img = scipy.misc.imread(path).astype(np.float)
  File "C:\Users\Baxter\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\utils.py", line 101, in newfunc
    return func(*args, **kwds)
  File "C:\Users\Baxter\AppData\Local\Programs\Python\Python35\lib\site-packages\scipy\misc\pilutil.py", line 164, in imread
    im = Image.open(name)
  File "C:\Users\Baxter\AppData\Local\Programs\Python\Python35\lib\site-packages\PIL\Image.py", line 2585, in open
    % (filename if filename else fp))
OSError: cannot identify image file '1527709726-madelbrot.jpg'


It technicaly downloads somthing, because I see the file name in the folder, but it says it cannot identify it. I cant even open it.

fmw42
  • 46,825
  • 10
  • 62
  • 80
  • 1
    Please fix the indentation in the code you posted. In the future, to post code, paste it in, select it, and click the `{}` widget. That will shift every line over 4 spaces, causing it to be rendered as code. Best to avoid tabs in the original code, especially with Python. – Jeff Learman May 30 '18 at 16:33
  • sorry. it wouldn't let me post it in the original way. thanks for the advice. this was my first post to stackoverflow – Alexander Lemieux May 30 '18 at 16:46
  • Thanks for reformatting. However, the error messages don't line up with your posted code. There is no call to `imread`, for example. Please run your posted code and post the corresponding errors. – Jeff Learman May 30 '18 at 18:35
  • this is probably because I removed all of the bot token info(if someone else had that they could edit my bot – Alexander Lemieux May 30 '18 at 18:55
  • Regardless, find a way to post a minimal example that shows your problem. The error messages here apply to code you haven't posted, so we can't possibly help you. It's OK to replace credentials with junk. Also, post the **minimum** code that shows your problem. See [Minimal, Complete, Verifiable Example](https://stackoverflow.com/help/mcve). – Jeff Learman May 30 '18 at 19:00
  • I didn’t want to post just the downloading part because I wanted to give everyone the full script so if Something else was causing the problem people could spot it. The other script refernenced in the script is someone else’s and I know it works. When I look up the image it downloaded, it can’t open it and it only contains 179 bytes. I’m on my school buss right now so I will edit my code later – Alexander Lemieux May 30 '18 at 19:11
  • You aren't writing the actual data you received into your files; you're writing a Base64 encoded version of the data, instead. – jasonharper May 30 '18 at 19:55
  • How would I go about writing the actual data to download an actual image(one that I can open and see) – Alexander Lemieux May 30 '18 at 19:58
  • I google "python base64" and I find https://stackoverflow.com/questions/3470546/python-base64-data-decode – Jeff Learman May 30 '18 at 22:08
  • Regarding avoiding stripping down to the minimum program that shows the bug: a huge part of the value of that is it shows you whether the bug is caused by something outside of where you're looking! In the future, please take the time to do it, because you'll often find the source of the problem in the process, and if you don't, you'll have a much better example to post. – Jeff Learman May 30 '18 at 22:10

0 Answers0