Skip to content

Instantly share code, notes, and snippets.

@szv99
Created November 27, 2023 20:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save szv99/f78c032736443fab51075bc45f9faf09 to your computer and use it in GitHub Desktop.
Save szv99/f78c032736443fab51075bc45f9faf09 to your computer and use it in GitHub Desktop.
RotateCookies by requests on Google services
import json
import random
from urllib.parse import parse_qs, parse_qsl, urlparse
import requests
import re
class Bard:
def __init__(self, timeout=6, proxies=None, session=None):
with open("API_KEYS.txt", "r") as f:
lines = f.readlines()
api_keys = {}
for line in lines:
key, value = line.strip().split(": ", 1)
api_keys[key.strip()] = value.strip()
self._BARD_API_KEY_1PSID = api_keys["_BARD_API_KEY_1PSID"]
self._BARD_API_KEY_1PSIDTS = api_keys["_BARD_API_KEY_1PSIDTS"]
self.proxies = proxies
self.timeout = timeout
self.headers = {
"Host": "bard.google.com",
"X-Same-Domain": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Origin": "https://bard.google.com",
"Referer": "https://bard.google.com/",
}
self.reqid = random.randint(pow(10, 3-1), pow(10, 3)-1)
self.conversation_id = ""
self.response_id = ""
self.choice_id = ""
if session is None:
self.session = requests.Session()
self.session.headers.update(self.headers)
self.session.cookies.update({
"__Secure-1PSID": self._BARD_API_KEY_1PSID,
"__Secure-1PSIDTS": self._BARD_API_KEY_1PSIDTS,
})
else:
self.session = session
self.SNlM0e = self._get_snim0e()
def _get_snim0e(self):
response = self.session.get("https://bard.google.com/", timeout=self.timeout, proxies=self.proxies, verify=False)
response.raise_for_status()
matches = re.findall(r'"SNlM0e":"(.*?)"', response.text)
matchesCfb2h = re.findall(r'"cfb2h":"(.*?)"', response.text)
self.cfb2h = matchesCfb2h[0]
self._set_cookie_refresh_data(response.text)
return matches[0]
def _set_cookie_refresh_data(self, input):
og_pid_regex = r'https:\/\/accounts\.google\.com\/ListAccounts\?authuser=[0-9]+\\u0026pid=([0-9]+)'
exp_id_regex = r'https:\/\/accounts\.google\.com\/RotateCookiesPage"],([0-9]+,[0-9]+,[0-9]+,[0-9]+,[0-9]+,[0-9]+)'
matches_og_pid = re.search(og_pid_regex, input)
matches_exp_id = re.search(exp_id_regex, input)
print(matches_og_pid, matches_exp_id)
if matches_og_pid:
og_pid_url = matches_og_pid.group(0)
og_pid_query = urlparse(og_pid_url.replace("\\u0026", "&")).query
print(og_pid_query)
og_pid = parse_qs(og_pid_query)['pid'][0]
print(f"og_pid: {og_pid}")
self.og_pid = og_pid
if matches_exp_id:
values_str = matches_exp_id.group(1)
values_array = [int(val) for val in values_str.split(',')]
print(f"Values array: {values_array}")
if len(values_array) >= 5:
rot = values_array[0]
exp_id = values_array[4]
# You can print or use rot and exp_id as needed
print(f"rot: {rot}")
print(f"exp_id: {exp_id}")
self.rot = rot
self.exp_id = exp_id
# Update cookies using the extracted og_pid and exp_id
update_cookies_url = f"https://accounts.google.com/RotateCookiesPage?og_pid={self.og_pid}&rot={self.rot}&origin=https%3A%2F%2Fbard.google.com&exp_id={self.exp_id}"
headers_google = {
'Host': 'accounts.google.com',
'Cookie': f'__Secure-1PSID={self._BARD_API_KEY_1PSID}; __Secure-1PSIDTS={self._BARD_API_KEY_1PSIDTS};',
'Referer': 'https://bard.google.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
}
try:
response = self.session.get(update_cookies_url, headers=headers_google, timeout=self.timeout, proxies=self.proxies)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
# Extract initValue from the updated cookies
print(response.text)
init_value_regex = r'init\(\'(-?\d+)\','
matches_init_value = re.findall(init_value_regex, response.text)
print(matches_init_value)
if matches_init_value:
self.init_value = matches_init_value[0]
self.update_1PSIDTS()
def update_1PSIDTS(self):
# Prepare request data
data = [self.og_pid, f'{self.init_value}']
data = json.dumps(data)
update_cookies_url = f"https://accounts.google.com/RotateCookiesPage?og_pid={self.og_pid}&rot={self.rot}&origin=https%3A%2F%2Fbard.google.com&exp_id={self.exp_id}"
# Update 1PSIDTS using the extracted og_pid and initValue
update_1psidts_url = "https://accounts.google.com/RotateCookies"
headers_rotate = {
'Host': 'accounts.google.com',
"Content-Type": "application/json",
'Cookie': f'__Secure-1PSID={self._BARD_API_KEY_1PSID}; __Secure-1PSIDTS={self._BARD_API_KEY_1PSIDTS};',
'Referer': update_cookies_url,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
}
# headers_rotate.update(self.headers)
response = self.session.post(update_1psidts_url, data=data, headers=headers_rotate, timeout=self.timeout, proxies=self.proxies)
response.raise_for_status()
# Extract updated 1PSIDTS from the response headers
cookie_headers = response.headers.get("Set-Cookie", "")
matches_1psidts = re.findall(r"__Secure-1PSIDTS=([^;]+)", cookie_headers)
print(cookie_headers)
if matches_1psidts:
new_1psidts = matches_1psidts[0]
# Update 1PSIDTS in API_KEYS.txt
with open("API_KEYS.txt", "r") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if line.startswith("_BARD_API_KEY_1PSIDTS:"):
lines[i] = f"_BARD_API_KEY_1PSIDTS: {new_1psidts}\n"
break
with open("API_KEYS.txt", "w") as f:
f.writelines(lines)
self._BARD_API_KEY_1PSIDTS = new_1psidts
# Update self.cookies
self.cookies = cookie_headers
bard_instance = Bard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment