K
K
Kayuro2022-04-20 15:49:05
Python
Kayuro, 2022-04-20 15:49:05

How to connect to a proxy, Python Requests?

There is a code that connects to a discord account using a token and sends messages with a delay from the database:

from random import choice
import requests as r
import time

s = r.Session()
s.headers['authorization'] = input('Token: ')
msg_set: list = open('msg.txt', 'r', encoding='utf-8').read().splitlines()
chat_id = input('Input chat id: ')
delay = int(input('Delay between messages in seconds: '))
total_sent = 0


while True:
    try:
        msg = choice(msg_set)
        print(f'Sending message {msg}')
        _data = {'content': msg, 'tts': False}
        resp = s.post(
            f'https://discord.com/api/v9/channels/{chat_id}/messages', json=_data).json()
        msg_id = resp['id']
        total_sent += 1
        print(f'Message sent (Already {total_sent} in total).')
        print(f'Sleeping {delay} seconds')
        time.sleep(delay)
    except Exception as e:
        print(f'Some error: {e}')
        time.sleep(20)

I want to add connection to proxy. I read the documentation, so I didn't really understand. Proxy will use personal socks5 or https with password and username.
Can you help in any way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2022-04-20
@SoreMix

I read the documentation, but I don't really understand

What exactly is unclear?
dock
626004919c603639050597.jpeg

Add your proxies to the dictionary, pass this dictionary as a parameter proxieswhen requesting
import requests 

proxies = {
    'http': 'socks5://31.220.43.141:31539',
    'https': 'socks5://31.220.43.141:31539'
}

r = requests.get('https://api.ipify.org/', proxies=proxies)

print(r.text)

T
TheMade, 2022-04-20
@TheMade

To use a socks5 proxy you need:
pip install -U requests[socks]
To use a proxy without a password, just don't write anything up to and including the "@" character.

import requests

proxy_list = [
{"https": "https://user:[email protected]:port"},
{"socks5": "socks5://user:[email protected]:port"}
]

r = requests.get("https://qna.habr.com", proxies=proxy_list)
print(r.text)

I haven't tested this code so please correct for syntax and other errors.
But I think you get the point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question