'Why did I lose my data in a Heroku Postgres (Hobby tier) database after I redeployed my project?
I'm trying to create currency commands for my Discord bot, which I've hosted on Heroku. For the database, I've connected my project to a Heroku Postgres DB, which works perfectly fine, except for the fact that I lose all my data when I redeploy my code. Currently, I use GIT Bash, because GitHub integration with Heroku is suspended.
Here is the Cog which holds my currency commands:
from discord.ext import commands
import discord
import random
from discord import Embed
import psycopg2
from discord_components import DiscordComponents, ComponentsBot, Button, SelectOption, Select
import os
import math
DATABASE_URL = os.environ.get('DATABASE_URL')
class BucksDB(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.membercash = []
self.convar = psycopg2.connect(DATABASE_URL)
self.cursor = self.convar.cursor()
@commands.Cog.listener()
async def on_ready(self):
print('BucksDB Cog Online')
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
time = error.retry_after
seconds = time % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
valst = "%d:%02d:%02d" % (hour, minutes, seconds)
emb = Embed(description='*Slow it down bud!*', colour = discord.Colour.random())
emb.add_field(name = 'This command is on cooldown for `{}`'.format(valst), value = '🤕')
await ctx.send(embed = emb)
@commands.command()
async def reconnect(self, ctx):
self.convar = psycopg2.connect(DATABASE_URL)
self.cursor = self.convar.cursor()
@commands.command()
async def showdb(self, ctx):
data = self.cursor.execute('SELECT * FROM records')
for i in list(data):
print(i)
@commands.command()
async def reset_bucks(self, ctx):
if ctx.message.author.id == <id>:
for guild in self.bot.guilds:
for member in guild.members:
self.membercash.append((member.id, 0))
self.membercash = list(set(self.membercash))
self.cursor.execute("DROP TABLE IF EXISTS records")
table = """CREATE TABLE records(
User_ID bigint NOT NULL PRIMARY KEY,
ChimkenBucks bigint
);"""
self.cursor.execute(table)
for i in self.membercash:
value = i
self.cursor.execute("INSERT INTO records VALUES {}".format(value))
self.convar.commit()
self.membercash = []
print('ChimkenBucks reset')
print()
@commands.command()
async def add_bucks(self, ctx):
if ctx.message.author.id == <id> :
for guild in self.bot.guilds:
for member in guild.members:
self.membercash.append((member.id, 0))
self.membercash = list(set(self.membercash))
for i in self.membercash:
value = i
self.cursor.execute("INSERT INTO records VALUES {}".format(value))
self.convar.commit()
self.membercash = []
print('New ChimkenBucks initialised')
print()
@commands.command()
async def show_bucks(self,ctx):
self.cursor.execute("SELECT * FROM records")
#recordslist = list(records)
x = self.cursor.fetchall()
for i in x:
print(i)
@commands.command(aliases = ['bal', 'money'])
async def cash(self, ctx):
id = ctx.author.id
file = open('money.txt', 'r')
gifs = file.readlines()
n = random.randint(0, len(gifs)-1)
url = gifs[n]
file.close()
self.cursor.execute("SELECT * FROM records WHERE User_ID ={}".format(id))
posessions = self.cursor.fetchall()
cash = list(posessions)[0][1]
emb = Embed(title = 'Wallet', color = discord.Colour.random())
emb.add_field(name = 'ChimkenBucks', value = f'{cash}❂')
emb.set_author(name = ctx.message.author, icon_url = ctx.author.avatar_url)
emb.set_footer(text = 'Here is your cash money ❂')
emb.set_thumbnail(url = url)
await ctx.send(embed = emb)
@commands.command(aliases = ['earn', 'job'])
@commands.cooldown(rate = 1, per = 300, type=commands.BucketType.user)
async def work(self,ctx):
try:
weight = random.randint(1,100)
if weight >= 1 and weight <=80:
cash = random.randint(1,50)
else:
cash = random.randint(50, 100)
emb = Embed(description = f'You earned {cash}❂!', colour = discord.Color.random())
emb.set_footer(text = 'cha-ching!')
emb.set_author(name = ctx.message.author, icon_url = ctx.author.avatar_url)
await ctx.reply(embed = emb)
id = ctx.author.id
self.cursor.execute("""UPDATE records
SET ChimkenBucks = ChimkenBucks+{}
WHERE User_ID = {}""".format(cash, id))
self.convar.commit
except commands.CommandOnCooldown :
await ctx.reply('Slow down, mate! ')
def setup(bot):
bot.add_cog(BucksDB(bot))
Every time I redeploy my code, I lose previous data.
I've tried pg:backups:capture followed by pg:backups:restore
When I do this, my Heroku Postgres Database disconnects from my project - for which I used the reset command that you will find in the code I included.
I would really love if someone could give me a detailed and structured answer to this, because I'm rather new to online hosting.
Thanks!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
