Как передавать изменяемые переменные между файлами python
учусь писать парсера с телеграм ботом на aiogram в двух разных файлах , с парсером вроде все получилось как и телеграм ботом , но возникла проблема мне бы хотелось вписывать значения в тг и после этого эти значения передавал в парсер (такие значения как цена , название предмета ), я пробовал через сохранение в txt файл , но как то не очень , так - же пробовал на прямую пишет файл цикличный. код тг бота
from aiogram import Bot , Dispatcher , executor , types
from aiogram.dispatcher.filters import Text
from aiogram.utils.markdown import hbold , hlink
from config import TOKEN
from bs4 import BeautifulSoup as bs
from fake_useragent import UserAgent
import time
import json
from normal_price import data_colected , curryncy
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State , StatesGroup
bot = Bot(TOKEN ,parse_mode=types.ParseMode.HTML )
dp= Dispatcher(bot , storage=MemoryStorage())
class fsm_serch(StatesGroup):
price_from = State()
price_to = State()
@dp.message_handler(commands='start')
async def start(message:types.Message):
start_buttons = ['Начать поиск', 'Поиск предмета', 'Задать параметры цены поиска' ]
keyboard= types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(*start_buttons)
await message.answer('пик', reply_markup=keyboard)
@dp.message_handler(Text(equals='Начать поиск'))
async def get_sale(message:types.Message):
await message.answer('Wait.....'+'\n'
"Выбрано поиск по выгоде"+'\n' 'Примерное время сбора информации 10 минут')
data_colected()
await message.answer('Почти готово'+'\n'
"Уже все..."
)
with open('result.json', encoding='utf-8') as file:
data = json.load(file)
for index ,item in enumerate(data):
card = card = f'{hlink(item.get("full_name"), item.get("img"))}\n' \
f'{hbold("Качество: ")}{item.get("full_float")}\n ' \
f'{hbold("Прайс: ")}{item.get("full_price")} {item.get ("full_currency") } \n ' \
f'{hbold("Прайс стим: ")}{item.get("steam_price")} {item.get ("full_currency") } \n ' \
f'{hbold("Выгода: ")}{item.get("benefit")} {item.get ("full_currency") }\n ' \
f'{hlink(("Ссылка стим "), item.get("steam_url"))}\n ' \
f'{hlink(("Ссылка маркета ") , item.get("url"))}\n ' \
f'{hlink(("Wiki CSGO "), item.get("Wiki money"))}\n '
if index%20==0:
print("Пауза")
time.sleep(3)
print("1")
print("2")
print("3")
await message.answer(card)
print("Конец")
await message.answer("Конец.")
@dp.message_handler(Text(equals='Задать параметры цены поиска'),state=None)
async def Set_Price(message:types.Message):
price_data.clear()
await fsm_serch.price_from.set()
await message.answer('Введите ОТ какой цены искать вещи.')
@dp.message_handler(content_types=['text'], state=fsm_serch.price_from)
async def price_from(message:types.Message, state: FSMContext):
global price_frome
price_frome = message.text
if price_frome.isdigit() is True:
await fsm_serch.next()
await message.answer('Введите ДО какой цены искать вещи.')
else :
await message.answer('Ведены недопустимые значения, попробуйте еще раз.')
@dp.message_handler(content_types=['text'], state=fsm_serch.price_to)
async def price_to(message:types.Message, state: FSMContext):
global price_too
price_too = message.text
if price_too.isdigit() is True:
if int(price_frome) < int(price_too):
await message.answer('Записал нужные значения.')
price_data.append({
"price_frome": price_frome,
"price_too": price_too
})
with open('options.json', 'w', encoding='utf-8') as file:
json.dump(price_data, file, indent=4 , ensure_ascii=False)
start_buttons = ['По выгоде', 'Поиск предмета', 'Задать параметры цены поиска' ]
keyboard= types.ReplyKeyboardMarkup(resize_keyboard=True)
keyboard.add(*start_buttons)
await message.answer('пик', reply_markup=keyboard)
await state.finish()
else :
await message.answer('Ведены недопустимые значения.')
else :
await message.answer('Ведены недопустимые значения, попробуйте еще раз.')
def main():
print("Бот запущен")
try:
executor.start_polling(dp)
except Exception as e:
print('таймаут')
time.sleep(15)
if __name__ == '__main__':
main()
код парсера
from email import header
from glob import glob
import json
from pickle import TRUE
import random
from unittest import skip
from urllib import response
from weakref import proxy
from wsgiref.headers import Headers
import requests
from bs4 import BeautifulSoup as bs
from fake_useragent import UserAgent
import time
import lxml
from requests import Session
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
import re
import multiprocessing
from multiprocessing import Pool
random_time = random.uniform(3, 5)
print (random_time)
ban_time = 235
ua = UserAgent()
result = []
try :
with open('options.json') as file:
open_price = json.load(file)
for pricess in open_price:
prices1 = prices1 = pricess.get("price_frome")
prices2 = prices2 = pricess.get("price_too")
price_on = prices1
price_off = prices2
except json.decoder.JSONDecodeError:
price_on = "50"
price_off = "1000"
curryncy = 'rub'
if curryncy == 'rub':
curryncy_steam = 5
elif curryncy == 'usd':
curryncy_steam = 1
search = ''
proxies = {
'http' : 'http://45.8.115.155:81'
}
price_difference = 1.15
page_number = 3
base_url = 'https://market.csgo.com'
sesi= Session()
s = Session()
s.headers.update({'User-Agent': ua.random,})
s.cookies.setdefault('_language', 'en')
s.get(base_url +'/currency/switch/' +curryncy)
def data_colected():
result.clear()
print("Произведена отчистка.")
for pages in range(1 , page_number + 1 , 1 ):
pages = str(pages)
print ( "Страница под номером" +" " + pages )
url = '?t=&t=all&p='+pages+'&rs='+price_on+';'+price_off+'&search='+search+'&sd=desc'
time.sleep(random.uniform(0.1 , 3))
response = s.get(good_url := base_url + url)
print (response)
print (good_url)
soup= bs(response.text, "lxml")
all_links = soup.find_all('a' , class_='item hot')
if all_links == []:
print('неверно')
else:
for link in all_links:
url1 = 'https://market.csgo.com' + link['href']
print(url1)
time.sleep(random.uniform(0.1 , 1.5))
responses = s.get(url1)
soup= bs(responses.text, "lxml")
try :
full_name = soup.find('div', class_='item-h1').find('h1').get_text(strip=True)
full_float = soup.find('div', class_='item-h1').find('span').get_text(strip=True)
full_price= soup.find('div', class_='ip-bestprice').__str__().replace('<div class="ip-bestprice">', '').replace('<small></small>', '').replace('</div>', '').replace('<small class="USD"></small>', '').strip()
full_price = full_price.replace(' ','')
if full_price == 'None':
full_price = 1
full_price = float( full_price )
full_currency = soup.find('div', class_=['currency-selector__item', 'active']).get_text(strip=True)
img = soup.find('div',class_='ip-pic')
img = img.findChildren('img')[0]
imge = img['src']
full_name= full_name.__str__().replace('|', '')
except AttributeError:
print('не получилось найти')
continue
#вики
steam_name =full_name.__str__().lower().replace(' ','/').replace(' ','-')
steam_float = "weapon"
if steam_float == "Container":
items = "cases"
if steam_float == "Agent":
steam_name = steam_name.__str__().lower().replace(' ','/').replace(' ','-').replace('.','').replace('/','-')
items = "agents"
if steam_float == "knife":
items = "knife"
if steam_float == "weapon":
items = "weapons"
wiki_money = "https://wiki.cs.money/ru/"+ items +"/"+steam_name
wiki_responses = requests.get(wiki_money)
if wiki_responses.status_code == 200:
wiki_url = wiki_money
else:
wiki_url = "Отсуствует"
#стим
steam_name = full_name.__str__().replace(' (Factory New)', '').replace(' (Minimal Wear)', '').replace(' (Field-Tested)', '').replace(' (Well-Worn)', '').replace(' (Battle-Scarred)', '')
steam_name = steam_name.__str__().replace('StatTrak™ ', 'StatTrak%E2%84%A2%20').replace("'", '%27').replace(" ", '%20%7C%20').replace(" ", '%20')
steam_float = full_float.__str__().replace('Прямо с завода', 'Factory New').replace('Немного поношенное', 'Minimal Wear').replace('После полевых испытаний', 'Field-Tested').replace('Поношенное', 'Well-Worn').replace('Закалённое в боях', 'Battle-Scarred').replace('Контейнер', 'Container').replace(' ', '%20')
time.sleep(random.uniform(0.1 , 3.5))
NMURL = "https://steamcommunity.com/market/priceoverview/?market_hash_name="+steam_name+"%20%28"+steam_float+"%29&appid=730¤cy="+str(curryncy_steam)
if steam_float == "Container":
steam_float = ''.__str__()
NMURL = "https://steamcommunity.com/market/priceoverview/?market_hash_name="+steam_name+steam_float+"&appid=730¤cy="+str(curryncy_steam)
if steam_float == "Sticker":
steam_float = ''.__str__()
NMURL = "https://steamcommunity.com/market/priceoverview/?market_hash_name="+steam_name+steam_float+"&appid=730¤cy="+str(curryncy_steam)
if steam_float == "Agent":
steam_float = ''.__str__()
NMURL = "https://steamcommunity.com/market/priceoverview/?market_hash_name="+steam_name+steam_float+"&appid=730¤cy="+str(curryncy_steam)
if steam_float == "Music Kit":
steam_float = ''.__str__()
NMURL = "https://steamcommunity.com/market/priceoverview/?market_hash_name="+steam_name+steam_float+"&appid=730¤cy="+str(curryncy_steam)
steam_name = full_name.__str__().replace(' ', '+').replace('StatTrak™', '%22StatTrak%E2%84%A2+')
steam_float = full_float.__str__().replace('Поношенное', '').replace('Прямо с завода', '').replace('После полевых испытаний', ' ').replace('Закалённое в боях', ' ').replace('Немного поношенное', ' ').replace(' ', '+')
url_steam ="https://steamcommunity.com/market/search?appid=730&q="+steam_name+"+"+steam_float
data = sesi.get(NMURL).json()
time.sleep(random.uniform(0.1 , 3))
try :
steam_price = data.get("lowest_price")
if steam_price == None:
steam_price = data.get("median_price")
if steam_price == None:
steam_price = 1
print("бан")
time.sleep(random.uniform(20 , 25))
steam_price = steam_price.__str__().replace(' pуб.','').replace(',','.').replace(' ','')
except AttributeError :
print("Неполучилось собрать")
steam_price = 1
price1 = int(float(full_price))
price2 = int(float(steam_price))
#отбор результатов
benefit= price2 - price1
benefit= str(benefit)
if price1 * price_difference <= price2 or price2 == 1 :
print("добавляем")
result.append(
{
"img": imge,
"full_name": full_name,
"full_float": full_float,
'full_price': full_price,
'steam_price': steam_price,
'benefit': benefit,
'full_currency': full_currency,
'url': url1,
'steam_url': url_steam,
'Wiki money' : wiki_url
}
)
with open('result.json', 'w', encoding='utf-8') as file:
json.dump(result, file, indent=4 , ensure_ascii=False)
print(len(result))
def data_steam():
steam_name = "SG 553 Cyrex".__str__().lower().replace(' ','/').replace(' ','-')
steam_float = "weapon"
if steam_float == "Container":
items = "cases"
if steam_float == "Agent":
steam_name = steam_name.__str__().lower().replace(' ','/').replace(' ','-').replace('.','').replace('/','-')
items = "agents"
if steam_float == "knife":
items = "knife"
if steam_float == "weapon":
items = "weapons"
wiki_money = "https://wiki.cs.money/ru/"+ items +"/"+steam_name
wiki_responses = requests.get(wiki_money)
if wiki_responses.status_code == 200:
print(wiki_money)
def main():
data_colected()
#data_steam()
if __name__ == '__main__':
main()
Прошу прощения за столь грязный код.
Ответы (2 шт):
Не совсем понял суть вопроса, однако если задача стоит в обмене переменными между двумя файлами - файлами бота и парсера, то можно импортировать в файл бота файл парсера, и вызывать в файле бота какие-либо функции из файла парсера. Точно так же и с переменными, просто перед выполняемым действием или вызываемым объектом используй синтаксис file.variable или file.func(), где file - файл file.py который импортируется, а variable и func() - это переменная и функция соответственно. Пример:
Файл Test.py:
Hello = 'world!'
def setup_value(a):
b = a + 2
return b
Файл Main.py (который и запускается):
import Test
print(Test.setup_value(3)) #запуск функции которая описана в test.py
print(Test.Hello) #получение переменной которая задается в test.py
Результат:
5
world!
Отвечая на задачу, описанную в комментарии, можно сделать вот так (врать не буду, решение не самое оптимальное, но лучше чем дозапись и чтение с текстового файла). Для этого создал один дополнительный файл для переменных и еще один файл для запуска всех функций. Создал глобальные переменные для большего вашего удобства при работе с асинхронными функциями:
parcer
import helper
def parcing():
global result
result = helper.price
telegram
import parcer
def input_info():
global data
data = input()
def output():
output_price = parcer.result
print(output_price)
helper
import telegram
def start():
global price
telegram.input_info()
price = telegram.data
launcher
import parcer
import telegram
import helper
main.start()
Test.parcing()
run.output()